tags:

views:

182

answers:

3

I have a class with several constructors and I want to call the "main" one from another - but using null.

Using just this(null) results in a compile time error, so I cast null to the type of the other constructor. Compiles fine.

MyClass
{
  public MyClass(SomeType t)
  { }

  public MyClass(IList<FooType> l)
    : this((SomeType)null)
  { }
}

This feels, lets just say icky. Is this okay and common or insane and shows a flaw in the class - in that it should have an empty constructor?

The class "mostly" requires a SomeType, but there are rare times when it is okay to not have one. I want the rare times to "stick out" and be obvious that something "is not a-typical" with the code.

+6  A: 

You need the cast because null by itself is ambiguous. A null by itself has no inherent type, so the cast tells the compiler which constructor you want to pass null to.

That being said, it is probably more meaningful for your class to use a default (no-arg) constructor, like you said. Having all three constructors is probably okay, too.

Loadmaster
I know why I need the cast - but seems strange to cast null to something, so I wanted to get a second opinion on how strange this scenario is.
quip
It's not uncommon to cast `null` to a specific type. It's one of the joys of overloaded methods.
Loadmaster
A: 

In my honest opinion this seems like a logic flaw, that will get you into trouble somewhere down the road. It just seems that at some point a piece of code will be written that will do some validation and break this constructor and you will waste a massive amount of time debugging it. I do need to further see what it is you are trying to do and why.

Woot4Moo
+5  A: 

It does have just a slight smell to it. This technique is used sometimes, but I would avoid it if practically possible.

A parameterless constructor is generally more descriptive than passing null, you can make it private if you only use it from within the class:

MyClass {

  private MyClass() {
  }

  public MyClass(SomeType t) {
  }

  public MyClass(IList<FooType> l) : this() {
  }

}

Another alternative (but one that doesn't work to call from a constructor) is to put the code in a static method to somewhat isolate it and give it a more descriptive name:

MyClass {

  public MyClass(SomeType t) {
  }

  public static MyClass CreateEmptyInstance() {
    return new MyClass((SomeType)null);
  }

}
Guffa