Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an implemented abstract property in the constructor causes CA2214: Do not call overridable methods in constructors

public abstract class MyBase
{
    public abstract bool MyProperty
    {
        get;
        protected set;
    }
}

public class MyClass : MyBase
{
    public MyClass()
    {
        this.MyProperty = true;
    }

    public override bool MyProperty
    {
        get;
        protected set;
    }
}

The constructor MyClass() causes CA2214:

Do not call overridable methods in constructors.

This normally only shows if one calls a virtual method defined in the same class as the constructor. e.g. Accessing MyProperty inside MyBase's constructor. Here I am calling a non-virtual overridden implementation of an inherited abstract property inside the derived class' constructor.

like image 521
Monstieur Avatar asked Jun 10 '13 07:06

Monstieur


1 Answers

No, it's still virtual, as override doesn't seal the member implicitly. (Try it: derive another class from MyClass, and you can override MyProperty again.)

You could seal it explicitly though:

public override sealed bool MyProperty
{
    get;
    protected set;
}

At that point I'd expect the warning to go away.

like image 180
Jon Skeet Avatar answered Sep 27 '22 17:09

Jon Skeet