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;
}
}
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:
And:
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.)