I have a struct type in C#. I want to be able to convert null
implicitly to this type. For instance, null
could be represented by a special value of the struct type and the cast operator should return a struct with this value.
In C++, I could use an implicit cast operator overload of type std::nullptr_t
. Is there a comparable type in C#?
I have had the idea to use a special NullType
class which has no instances. This works but looks somehow ugly. Is there a better way?
Example:
class NullType
{
private NullType(){} // ensures that no instance will ever be created
}
struct X
{
private static readonly int nullValue = -1;
private int val;
public X(int val){ this.val= val; }
public static implicit operator X(NullType t)
{
return new X(nullValue);
}
}
class MainClass
{
public static void Main(string[] args)
{
X x = null; // Works now!
}
}