The compiler warns me that the Do static method in Class2 must have the new
keyword. It also adds one implicitly.
I'm trying to figure out the reason for that. These are class methods, not
instance methods, virtual/override are not an option, why is new needed?
Thanks,
Danny
The full warning message gives you a hint:
class1.cs(16,28): warning CS0108: The keyword new is required on 'StaticDo.Class2.Do()' because it hides inherited member
'StaticDo.Class1.Do()'
i.e.
public class Class1 {
public Class1() {}
public static void Do () {}
}
public class Class2 : Class1 {
public Class2() {}
// use new key word in the method declaration
public static new void Do () {}
}
in essence the compiler is requesting that with the "new" keyword you tell it that you are aware that you will be hiding the Class1
version of Do() in Class2 - i.e. "yes - go ahead hide the ancestor version - I know what I'm doing".
Usually when you try to override a method in its descendent the ancestor method needs to the marked as "virtual" while the deriving
method is marked as "override" e.g.:
public class Class1 {
public virtual void Do () {}
}
public class Class2 : Class1 {
public override void Do () {}
}
As you have discovered "virtual" and "override" are restricted to instance methods.
http://msdn.microsoft.com/library/en-us/csref/html/vclrfVirtualPG.asp
http://msdn.microsoft.com/library/en-us/csref/html/vclrfOverridePG.asp
http://msdn.microsoft.com/library/en-us/csref/html/vclrfStaticPG.asp
By declaring the methods "static" the Do() methods become class methods, i.e. the method does not act on any particular instance
created by the class.
I suspect that the C# equivalent of the "virtual function pointer table (vtable)" is stored in the class instance (object), not the
class, which would explain why class methods cannot use "virtual" and "override".
So why are you trying redefine a class function? Polymorphism applies to instances (objects), not classes.
As you can have to access the class method only through the class anyway give the methods different names - that way the Class2.Do()
will not hide Class1.Do().