In C#, is it safe to call virtual method from constructor? [duplicate]
Possi开发者_开发百科ble Duplicate:
Virtual member call in a constructor
In C#, is it safe to call virtual method from constructor? What does the language specification say? Please quote from the spec as well. By safe, I mean would it call the implementation of the derived class?
This doubt exists in my mind, because in C++, it is not safe to call virtual function from constructor.
You can do it, but you shouldn't. I think C# even gives you a warning for it.
It becomes very dangerous when the function has been overridden by a derived class, because you're now calling into that function before the derived class's constructor has been called.
It's not safe, since the virtual function would be called before the matching constructor has had a chance to establish the class invariants.
In contrast, it IS safe in C++ -- the function which is called is called during the matching constructor, not before.
精彩评论