Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual member call in a constructor

I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor.

Why would this be something not to do?

like image 962
JasonS Avatar asked Sep 23 '08 07:09

JasonS


People also ask

Is it legal to call a virtual method from within a constructor?

Calling virtual methods in constructor/destructor in C++ All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual function in a constructor.

Can we call virtual function in constructor in C#?

The C# strategy of calling the version of VFunc() matching the actual runtime type is the only possibility of getting anything except a runtime exception when an abstract function is called in a constructor.

What is virtual member in C#?

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member. By default, methods are non-virtual.

Can you call abstract method from abstract class constructor in C#?

Question: Can you call an abstract method from an abstract class constructor? Answer: Yes.


Video Answer


1 Answers

When an object written in C# is constructed, what happens is that the initializers run in order from the most derived class to the base class, and then constructors run in order from the base class to the most derived class (see Eric Lippert's blog for details as to why this is).

Also in .NET objects do not change type as they are constructed, but start out as the most derived type, with the method table being for the most derived type. This means that virtual method calls always run on the most derived type.

When you combine these two facts you are left with the problem that if you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called.

This problem is, of course, mitigated if you mark your class as sealed to ensure that it is the most derived type in the inheritance hierarchy - in which case it is perfectly safe to call the virtual method.

like image 194
Greg Beech Avatar answered Sep 19 '22 15:09

Greg Beech