Jacek
Jacek

Reputation: 12053

Can a constructor include logic that determines which other constructor overrides to call?

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

Answers (3)

srsyogesh
srsyogesh

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

Ondrej Svejdar
Ondrej Svejdar

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

Stochastically
Stochastically

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

Related Questions