Can I overload the cast from null statement in C #?

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(){} // 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!
     }
}
+4
source share
1 answer

, , , aka null, null.

:

public static implicit operator X(object t)

, , . (t ).

, , , , , , - . : null "just" (X.Null).

+1

Source: https://habr.com/ru/post/1598223/


All Articles