Reputation: 12053
It is posible in C# to decide in constructor, which other override constructor use? This below code doesn't compile! I don't know which invocation use.
public IntRange(int val, bool isMax)
: isMax ? this() : this()
{
if (isMax)
{
IntRange(0, val);
}
else
{
IntRange(val, int.MaxValue);
}
}
Upvotes: 5
Views: 364
Reputation: 609
It does not compile because of the statement isMax ? this() : this() in a constructor after : you can only call base class constructor or overloaded constructors of same class .
Upvotes: 0
Reputation: 22054
How about:
class IntRange {
public IntRange(int val, bool isMax)
: this(isMax ? 0 : val, isMax ? val : int.MaxValue) {
}
public IntRange(int min, int max) {
}
}
Upvotes: 9
Reputation: 7836
You could achieve that kind of thing using a static method on the object as follows
class IntRange {
public IntRange(int min, int max) {
// write code here
}
public static IntRange Construct(int val, bool isMax) {
if (isMax) {
return new IntRange(0, val);
} else {
return new IntRange(val, int.MaxValue);
}
}
}
You could even make the constructor public IntRange(int min, int max)
private, to force use of the static method.
I find that static methods to construct objects like that are particularly useful when one might want to create a subclass instead.
Upvotes: 2