Virtual member call in a constructor when assigning value to property

Posted by comecme on Stack Overflow See other posts from Stack Overflow or by comecme
Published on 2011-01-07T12:50:04Z Indexed on 2011/01/07 12:53 UTC
Read the original article Hit count: 281

I have an Abstract class and a Derived class. The abstract class defines an abstract property named Message. In the derived class, the property is implemented by overriding the abstract property. The constructor of the derived class takes a string argument and assigns it to its Message property. In Resharper, this assignment leads to a warning "Virtual member call in constructor".

The AbstractClass has this definition:

public abstract class AbstractClass {
    public abstract string Message { get; set; }

    protected AbstractClass() {
    }

    public abstract void PrintMessage();
}

And the DerivedClass is as follows:

using System;

public class DerivedClass : AbstractClass {
    private string _message;

    public override string Message {
        get { return _message; }
        set { _message = value; }
    }

    public DerivedClass(string message) {
        Message = message; // Warning: Virtual member call in a constructor
    }

    public DerivedClass() : this("Default DerivedClass message") {}

    public override void PrintMessage() {
        Console.WriteLine("DerivedClass PrintMessage(): " + Message);
    }
}

I did find some other questions about this warning, but in those situations there is an actual call to a method. For instance, in this question, the answer by Matt Howels contains some sample code. I'll repeat it here for easy reference.

class Parent {
    public Parent() {
        DoSomething();
    }
    protected virtual void DoSomething() {};
}

class Child : Parent {
    private string foo;
    public Child() { foo = "HELLO"; }
    protected override void DoSomething() {
        Console.WriteLine(foo.ToLower());
    }
}

Matt doesn't describe on what error the warning would appear, but I'm assuming it will be on the call to DoSomething in the Parent constructor. In this example, I understand what is meant by a virtual member being called. The member call occurs in the base class, in which only a virtual method exists.

In my situation however, I don't see why assigning a value to Message would be calling a virtual member. Both the call to and the implementation of the Message property are defined in the derived class.

Although I can get rid of the error by making my Derived Class sealed, I would like to understand why this situation is resulting in the warning.

© Stack Overflow or respective owner

Related posts about c#

Related posts about properties