Calling a specific constructor in C# with null

c#, constructor

Solution

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.

Problem

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.

Original source