5

Possible Duplicate:
Virtual member call in a constructor

First of all, why isn't it an error to call a virtual function inside a ctor in C#?
Second of all, if it is allowed, why does Resharper still warn about it?

0

2 Answers 2

3

Already answered:

Virtual member call in a constructor

In short, it has something to do with the order in which the constructors are called, which is different from the order in which the virtual methods are called: constructors are called from the less specific to the most specific, while virtual methods are called from the most specific to the less specific.

It means you can fall into this trap:

public class Base {
  protected virtual void DoSomething() {
    // do nothing
  }

  public Base() {
    DoSomething();
  }
}

public class Another : Base {
  private List<string> list;

  public Another() {
    list = new List<string>();
  }

  protected override void DoSomething() {
    // this code will raise NullReferenceException,
    // since this class' constructor was not run yet,
    // still, this method was run, since it was called
    // from the Base constructor
    list.Add("something");
  }
}
2

As to why it isn't an error, check this from Wikipedia:

For some languages, notably C++, the virtual dispatching mechanism has different semantics during construction and destruction of an object. While it is recommended that virtual function calls in constructors should be avoided for C++ [3], in some other languages, for example Java and C#, the derived implementation can be called during construction and design patterns such as the Abstract Factory Pattern actively promote this usage in languages supporting the ability.

As for the second part of your question, ReSharper warns about it because while it may be allowed it can produce some unexpected results if you're not aware of what you're doing. For more details, check out:

Virtual member call in a constructor

Not the answer you're looking for? Browse other questions tagged or ask your own question.