1) Is it really necessary to define a method as virtual if it has no implementation? Of course, you can simply overwrite it in a subclass without using virtual ones and override it?
As stated in other answers, virtual methods must have implementations. You confuse it with abstract .
If you asked the question whether virtual methods should be declared that should have an implementation, virtual : In C #, yes, this is necessary. In Java, you can override any old method. C #'s solution was to require an override, which can be resolved using the virtual , so methods cannot be overridden if they are not intended for the programmer.
If the programmer has not expressed his intentions without using virtual , you can still override the methods using the new keyword. However, this works differently. Hope this code helps illustrate the concept:
class Program { static void Main(string[] args) { var baseC = new BaseClass(); var extC = new ExtClass(); var lazyC = new LazyClass(); Console.WriteLine(baseC.NewMethod()); Console.WriteLine(baseC.VirtualOverrideMethod()); Console.WriteLine("---"); Console.WriteLine(extC.NewMethod()); Console.WriteLine(extC.VirtualOverrideMethod()); Console.WriteLine("---"); Console.WriteLine(((BaseClass) extC).NewMethod()); Console.WriteLine(((BaseClass) extC).VirtualOverrideMethod());
Output:
NewMethod of BaseClass VirtualOverrideMethod of BaseClass --- NewMethod of ExtClass VirtualOverrideMethod of ExtClass --- NewMethod of BaseClass VirtualOverrideMethod of ExtClass --- VirtualOverrideMethod of BaseClass
2) If (1) is incorrect, I understand correctly that each virtual method must be redefined in a subclass using it ....
Not at all. virtual is a way of saying, "It's okay if you want to override this method." In fact, I included LazyClass in my code above to show this.
The above does not make the compiler complain ...
I have not used the interfaces a lot, but this seems like one thing. In my code, if I change
class ExtClass : BaseClass { public new string NewMethod() { return "NewMethod of ExtClass"; } public override string VirtualOverrideMethod() { return "VirtualOverrideMethod of ExtClass"; } }
in
class ExtClass : BaseClass { public new string NewMethod() { return "NewMethod of ExtClass"; } public override string VirtualOverrideMethod() { return "VirtualOverrideMethod of ExtClass"; } }
I get:
error CS0501: 'OverrideTest.Program.ExtClass.VirtualOverrideMethod()' must declare a body because it is not marked abstract, extern, or partial
From Visual Studio 2010. The same goes for the virtual method of my BaseClass .