a basic question popped in my head this morning. Here it is:
Is there any difference between doing this:
public class MyClass
{
private object _myField = new object();
...
}
and doing the following:
public class MyClass
{
private object _myField;
public MyClass()
{
_myField = new object();
}
...
}
Just to demonstrate casperOne’s point…
Here the base class constructor calls an abstract method implemented in the child class – this means we get to see the state of the object before its constructor body starts executing. The results are here:
As you can see, the variable initializer has already executed – but in the case where initialization only occurs in the constructor body,
foostill has its default value of null.Calling virtual methods from constructors is generally a very bad idea for precisely this sort of reason.