Skip to main content

Virtual member call in constructor

In This Article

CodeRush Classic shows the Virtual member call in constructor code issue if a constructor contains a call to a virtual member, which may cause unexpected results if the type will be inherited.

#Fix

Make the called member non-virtual.

#Purpose

Highlights the constructors containing a virtual member call, because it denotes an unsafe code.

#Example

public class MyClass
{
    public MyClass()
    {
        Name = GenerateDefaultName();
    }
    protected virtual string GenerateDefaultName()
    {
        return this.GetType().Name + "_obj";
    }
    public string Name { get; set; }
}

Fix:

public class MyClass
{
    public MyClass()
    {
        Name = GenerateDefaultName();
    }
    private string GenerateDefaultName()
    {
        return this.GetType().Name + "_obj";
    }
    public string Name { get; set; }
}