Warning about calling overridable auto-property when using generics

Question

Consider the following hierarchy:

public abstract class Base<T>
{
    protected abstract T N { get; set; }
}

public abstract class Intermediate<T> : Base<T>
{
    protected override T N { get; set; }
}

public class Derived : Intermediate<int>
{
    public Derived() { N = 1; }
    protected override sealed int N { get; set; }
}

Running the Visual Studio 2015 Professional Code Analysis produces the warning

Warning CA2214  'Derived.Derived()' contains a call chain that results in a call to a virtual method defined by the class. Review the following call stack for unintended consequences: 

Derived..ctor()
Base<T>.set_N(T):Void

This is similar to another Stack Overflow question, yet different as the property in Derived has been marked as sealed.

On the other hand, the piece of code below, not using any generics, does not produce any warnings:

public abstract class Base
{
    protected abstract int N { get; set; }
}

public abstract class Intermediate : Base
{
    protected override int N { get; set; }
}

public class Derived : Intermediate
{
    public Derived() { N = 1; }
    protected override sealed int N { get; set; }
}

Similarly, if I skip the intermediate class and instead derive Derived from Base, the warning disappears, even in the generic case. On the other hand, if I remove the sealed modifier for the latter example, the warning reappears, as expected.

So, is this working as intended in the generic case? And if so, what is an example where one should be careful?


Show source
| generics   | c#   | inheritance   | visual-studio   | code-analysis   2016-12-25 19:12 0 Answers

Answers ( 0 )

◀ Go back