C# FAQ: How call a virtual method from a constructor or destructor

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

How call a virtual method from a constructor or destructor?

In C++, objects are constructed from base class to derived class. This means that when the base class constructor is running the object is effectively a base object. So, C++ virtual method calls are directed to the base class implementation.

In .NET on the other hand, the derived constructor is executed first. This means the object will be a derived object; and, virtual method calls are directed to the derived implementation.

The C# compiler inserts a call to the base class constructor at the beginning of any derived constructor in order to maintain OO semantics, i.e. that the base class constructor is called first.

In a similar fashion, when C# destructors call virtual methods, virtual method calls from a base destructor are directed to the derived implementation.

Therefore, in C#, a virtual method can be called from a constructor or destructor. But, usually, it is a bad idea. .NET object construction is very different from C++ object construction; and, virtual method calling is affected.


See also


Personal tools