TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Administrator
Tech Writer
2.2k
1.5m
inheritance polymorphism with static members
Mar 9 2003 5:28 AM
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
Reply
Answers (
3
)
XML question
Low Level Sound Controls