views:

79

answers:

3

I have a class (Class B) that inherits another class (Class A) that contains virtual methods.

Mistakenly, I omitted the override keyword when declaring a (supposed to be) overriding method in Class B.

Class A

public class ClassA{
    public virtual void TestMethod(){
    }
}

Class B

public class ClassB : ClassA{
    public void TestMethod(){
    }
}

The code compiled without a problem. Can anyone explain why?

A: 

class B should be

public class ClassB : ClassA{
    public override void TestMethod(){
    }
}

but it can compile without the override - it should generate a warning that if it was intended you need to add the new keyword

public class ClassB : ClassA{
    public new void TestMethod(){
    }
}

checkout this for more information

Itay
-1: Not what he asked
John Saunders
sorry - i will edit the answer in a minute
Itay
+7  A: 

It's not ambiguous. It should compile with a warning to say that you should either specify "new" or "override" and that the default is effectively "new".

It definitely gives a warning when I try to compile that code - when you say it compiles "fine" and "without a problem" are you ignoring warnings?

Jon Skeet
Indeed I have warnings not being displayed - thanks for this, will put warnings on again.
Jimbo
What scope will the `new` method have in this case? If `override` essentially aborts the old method, then `new` must create a level of access for that method?
Jimbo
@Jimbo: I'm not sure what terminology you're really using here - "aborts" and "level of access" aren't really applicable here. But basically if you call `TestMethod` on a reference with a compile-time type of `ClassA` it will call the original method, and if you use a reference with a compile-time type of `ClassB` it will use the derived class method.
Jon Skeet
+1  A: 

The C# compiler generates a warning. I advice you to always compile with 'warnings as errors'.

Steven