3
Reply

inheritance polymorphism with static members

Administrator

Administrator

Mar 9 2003 5:28 AM
2k
Hi all, Am I right in thinking that C# doesn't include polymorphism for static variables? Here's an example - lets say I want a supertype to define a method that prints out the name of the class. So I create the following: class Parent { static protected string className; static Parent() { className = "Parent"; } static public void OutputClassName() { System.Console.Out.WriteLine( className ); } } class ChildA : Parent { static ChildA() { className = "ChildA"; } } class ChildB : Parent { static ChildB() { className = "ChildB"; } } And I run the following code: Parent.OutputClassName(); ChildA.OutputClassName(); ChildB.OutputClassName(); Now I'd expect the output to be Parent ChildA ChildB but it's actually Parent Parent Parent So it seems to me that when OutputClassName is invoked, and accesses the static className variable, it doesn't treat this variable polymorphically, e.g. the variable's value doesn't change depending on what class is used to invoke OutputClassName. When I step through the above code in a debugger, the derived class's static ctors are never called - even if ChildA.OutputClassN ame() is the first method called. Is this what is meant when MS say that static constructors are not inherited? I'd love for someone to explain what's going on here, and if there's a nice elegant way to implement functionality similar to above. TIA, Pete

Answers (3)