Tom said:
I am aware of the problems doing this in C++, but are there pitfalls also in
C#? I was under the impression that this problem was fixed in C#.
The problems are different than they were in C++, because the order of
initialization is different.
In C++, the object is constructed from the base on up, so when you call
a virtual method from a base class constructor, you end up calling the
base class's own implementation of that method, because the "upper
layers" of the class you are constructing are not yet there at that point.
In C#, the object is constructed the other way round, or for most
intents and purposes it would be correct to say that it's constructed in
one go. So when calling a virtual method from a base class, you actually
end up in the derived class's method. Whether this is a good idea to use
depends on what exactly you do in that derived method: you must be aware
that any instance fields of the derived class haven't been initialized
yet and that the derived class's own constructor code has not yet been
run. As Jon and I discussed, sometimes this is a good thing to be able
to use, but it's important that you are aware of the fact that a virtual
method is going to be called from a base class constructor when you
override it in a derived class.
Oliver Sturm