Skip to main content

Constructor cannot call itself

In This Article

CodeRush Classic shows the Constructor cannot call itself code issue if a constructor calls itself.

#Fix

Remove the invalid call or replace it with the call to another constructor.

#Purpose

Highlights the constructor declaration statements, which would cause the Constructor cannot call itself compilation error.

#Example

public class MyClass
{
    public MyClass()
    {
        Name = "Default";
    }
    public MyClass(int value)
        :this(value)
    {
        Value = value;
    }
    public string Name { get; private set; }
    public int Value { get; set; }
}

Fix:

public class MyClass
{
    public MyClass()
    {
        Name = "Default";
    }
    public MyClass(int value)
        :this()
    {
        Value = value;
    }
    public string Name { get; private set; }
    public int Value { get; set; }
}