rspec/rules/S1699/csharp/rule.adoc
2021-01-27 13:42:22 +01:00

42 lines
1.1 KiB
Plaintext

Calling an overridable method from a constructor could result in failures or strange behaviors when instantiating a subclass which overrides the method.
For example:
* The subclass class constructor starts by calling the parent class constructor.
* The parent class constructor calls the method, which has been overridden in the child class.
* If the behavior of the child class method depends on fields that are initialized in the child class constructor, unexpected behavior (like a ``++NullReferenceException++``) can result, because the fields aren't initialized yet.
== Noncompliant Code Example
----
public class Parent
{
public Parent()
{
DoSomething(); // Noncompliant
}
public virtual void DoSomething() // can be overridden
{
...
}
}
public class Child : Parent
{
private string foo;
public Child(string foo) // leads to call DoSomething() in Parent constructor which triggers a NullReferenceException as foo has not yet been initialized
{
this.foo = foo;
}
public override void DoSomething()
{
Console.WriteLine(this.foo.Length);
}
}
----
include::../see.adoc[]