views:

112

answers:

4

I have two constructors

MyObj(String s){ //first constructor
    ...
    if(s==null) s = somecode;
            this.s = s;
    ...
}

MyObj(): this(null) { } //second constructor

In this way, if the empty constructor is called, it will redirect to the first constructor and initialise the value as determined by some code.

However, now I have a third constructor

MyObj(Stream st){ //third constructor
    ...
}

Now the second constructor has no idea whether it is supposed to call the first constructor or the third. How do I tell it to call the first constructor? I tried MyObj(): this(String s = null) and it doesn't work either.

+9  A: 

Maybe: MyObj(): this((string) null) {}?

cdmckay
hey, it works! Now I feel embarassed that this solution didn't occur to me
Louis Rhys
Glad I could help :)
cdmckay
+1  A: 

I often find it easier to protect my sanity by using an initialization method for classes with several constructors. A single

private void Init(string str, Stream stream, bool doOtherStuff)
{
    // do stuff, replace nulls with defaults, etc
}

that gets called by every constructor, allowing the constructor itself to do its own thing. I really dislike constructors calling other constructors because it can get confusing easily, and something might not get initialized... or something can get initialized more than once.

Siege
+1  A: 

I agree with Siege. Don't try to chain constructors, instead use an Init function that can be called as needed from each ctor.

DevinEllingson
A: 

Adding my bit.

I would also suggest replacing multiple constructors with static CreateXXX methods, and rather make the constructor private.

This will be more explicit to the user of your class, wherein user can call the create method that he is interested in and pass the relevant parameters only. And not worry about what else is there in the object.

Amby