0

I got a warning message from ReSharper that "virtual member call in constructor" on Classification = new T(); :

public abstract class Creature<T> where T : new() {

     protected Creature()
     {
        Classification = new T();
     }

    public abstract T Classification { get; protected set; } 
}

public class Dog : Creature<Animal>
{
    public override Animal Classification { get; protected set; }

}

public class Animal{

public void AnimalSpecificMethod() { }

}

How can I solve this prolbem? Maybe an idea to re-design this structure?

What I would like to achieve is to create the same class type in Dog class what contains the Classification as it has declared through the Creature class.

Thank you!

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
user1692315
  • 129
  • 3
  • 10
  • 5
    Does the Classification property really need to be abstract? Will you ever do anything specific in the getter and setter? If not, just make it non-abstract (and non-virtual). – Thomas Levesque Mar 03 '14 at 15:04
  • 2
    Possible duplicate of http://stackoverflow.com/questions/119506/virtual-member-call-in-a-constructor?rq=1 – Patrick Hofman Mar 03 '14 at 15:05
  • The warning is because you are calling a method of a derived class before the derived class has been constructed... It could leave you open to exceptions because properties of the derived class haven't been initialised. Simplest thing is to create an init function – Dave Lawrence Mar 03 '14 at 15:07
  • Auto implemented properties are evil? – John Alexiou Mar 03 '14 at 15:16

1 Answers1

0

The problem is that this call, in the constructor, is a virtual call to the setter:

Classification = new T();

You could instead add a field backed property, which would avoid the issue:

protected Creature()
{
  _classification = new T();
}

private T _classification;

public virtual T Classification
{
  get { return _classification; }
  protected set { _classification = value; }
}

This does seem like a strange design, but I can't offer any specific design advice without more details of what you're trying to achieve. The Dog / Classification example is too general for specific suggestions. The above change will get around your immediate problem.

Rich
  • 15,048
  • 2
  • 66
  • 119