I have a structure type in C #. I want to be able to convert nullimplicitly to this type. For example, it nullcan be represented by a special value of type struct, and the cast operator must return a structure with this value.
In C ++, I can use implicit operator type operator overloading std::nullptr_t. Is there a comparable type in C #?
I had the idea of using a special class NullTypethat has no instances. It works, but it looks somehow ugly. Is there a better way?
Example:
class NullType
{
private NullType(){}
}
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;
}
}
source
share