C# Recursion – Why Can’t a Constructor Call Itself

cconstructorsrecursion

I am currently porting the class NumberRange from Java to C#.

I am writing this constructor and I wonder whether I can call a constructor in itself. Something like this:

public NumberRange(Double num1, Double num2)
{
    if (num1 <= num2)
    {
        Min = num1;
        Max = num2;
    }
    else
    {
        NumberRange(num2, num1);
        // Min = num2;
        // Max = num1;
    }
}

.NETFiddle

This is not a big deal, but I am curious. I think it is to prevent messing with constructor by creating a Stack Overflow during a class creation.

So, why can't I call a constructor in itself?

Edit:

I remind that my question was about the "why" and not the "how". If you ask yourself how I implemented this, just read my code here.

Best Answer

The issue seems to be not the recursion, but with invoking the constructor at all. See below:

class NumberRange
{
    public double Min { get; set; }
    public double Max { get; set; }

    public NumberRange(double num1, double num2)
    {
        if (num1 <= num2)
        {
            Min = num1;
            Max = num2;
        }
        else
            NumberRange(num2, num1); // illegal!!
    }

    public void AFunction()
    {
        NumberRange(1, 2); // also illegal!!
        this.NumberRange(1, 2); // 'this' keyword doesn't help
    }
}

And:

new NumberRange(1, 2).NumberRange(2, 1); // can't invoke the constructor on an object either

Obviously in your case the recursion was completely unnecessary, but if you have code which must be "recursable" - or just available outside of the context of instantiating a class - that code must be in a non-constructor function.

See this answer for why it is OK to call methods from constructors in C#. (In short, C# handles virtual method calls in ctors as one might hope.)