Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I overload a "cast from null" operator in C#?

Tags:

c#

null

struct

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!
     }
}
like image 745
gexicide Avatar asked Nov 09 '22 09:11

gexicide


1 Answers

No, conversion operators only allow conversion from types, not from a specific value of a type, aka null, so there is no null conversion operator.

The best fitting operator without introducing own types would be this:

public static implicit operator X(object t)

But obviously you don't want to use this. It isn't very safe to use (t can be any value, and the only way to handle non-null cases in an exception).

That said, I think the way you've created it now, using a class that can't be initialized is the best way to do this. In fact the only question is: why do you want to use null, instead of 'just' an default value instance on your struct (X.Null).

like image 125
Patrick Hofman Avatar answered Nov 14 '22 23:11

Patrick Hofman