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
| 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
- Are C# constructors inherited?
- How can one constructor call another?
- Are constructors the same in C++ and C#?
- Are destructors the same in C++ and C#?
- How call a virtual method from a constructor or destructor?
- How do destructors work in C#?
- How enforce constructor correctness in C#?
- How make a C# destructor virtual?
- What are the differences between C# and Java constructors?
- What are the differences between C# finalizers and Java destructors?
- What is the syntax for calling an overloaded constructor from within a constructor?
- Why must
structconstructors have at least one argument?