Resharper warns about using a virtual function in the constructor, but unlike C ++ this is not an error

Possible duplicate:
Virtual call of the participant in the constructor

Firstly, why is there no error for calling a virtual function inside ctor in C #?
Secondly, if allowed, why is Resharper still warning about this?

+3
source share
2 answers

Already answered:

Virtual call of the participant in the constructor

, - , , , : , .

, :

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");
  }
}
+3

, , :

, ++, . , ++ [3], , Java #, Factory , .

, ReSharper , , , , , . , :

+2

Source: https://habr.com/ru/post/1755344/


All Articles