how to create a null string?
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 开发者_JS百科MyObj(): this(String s = null)
and it doesn't work either.
Maybe: MyObj(): this((string) null) {}
?
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.
I agree with Siege. Don't try to chain constructors, instead use an Init function that can be called as needed from each ctor.
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.
I think that it would be better the next piece of code.
MyObj(String s) //first constructor
{
...
this.s = s;
...
}
MyObj() //second constructor
{
this(somecode);
}
MyObj(Stream st) //third constructor
{
...
}
My example shows that you could avoid checking on null at first constructor. Usage of second constructor in case, where string s from first constructor is nullable, improves readability your code
精彩评论