Search code examples
c#constructorwarningsvirtual-functions

virtual member call in constructor c#


In the constructor of my abstract ClassA, I am calling a virtual method and I am getting a warning from the compiler. I have included the links to the relevant documentation from Microsoft and NDepend. Here is my code:

https://msdn.microsoft.com/en-us/library/ms182331.aspx

https://www.ndepend.com/default-rules/Q_Constructor_should_not_call_a_virtual_method.html

public abstract class ClassA
{
    private int m_number;
    protected ClassA()
    {
         m_number = GetNumber()
    }

    protected abstract int GetNumber(); 
}

public class ClassB : ClassA
{
    public ClassB() : base()
    {
    }

    protected override int GetNumber()
    {
        return 10;
    }    
}

If I change my code in ClassA to call the virtual method indirectly through another method, I don't get any warnings. I'm not sure if this new design is better or what advantages it may have over the previous one. Here is the new code:

public abstract class ClassA
{
    private int m_number;
    protected ClassA()
    {
         m_number = GetNumberIndirectly()
    }

    private int GetNumberIndirectly()
    {
        return GetNumber();
    }

    protected abstract int GetNumber(); 
}

I would like to know if the new design is better and what advantages it may have over the previous one.


Solution

  • This could be an alternative way:

    public abstract class ClassA
    {
        private int m_number;
        protected ClassA(int n)
        {
             m_number = n;
        }
    
        //protected abstract int GetNumber(); 
    }
    
    public class ClassB : ClassA
    {
        public ClassB() : base(10)
        {
        }
    
        //protected override int GetNumber()
        //{
        //    return 10;
        //}    
    }