Search code examples
c#genericsnullableunary-operator

How can I declare a new operator "!??" (test object is not null)


Is there a way to declare a unary operator such as '!??'

I imagine something like this (non working code)

public bool operator !??<T> (this <T> item) {
    return item != null;
}

so I would use it like such

// day is a value and might possibly be null
string greeting = name !?? "hello there " + name;

I find myself often having to do this awkwardness

// day is a value and might be null
string greeting = day != null ? "hello there " + name : "";

It's fairly clear in the example I've provided, but when you are using getter/setters for view-models, it gets a bit confusing to stare at, and raises the chance of a logical error being missed. As such:

public DateTime? SearchDate {
    get { return _searchDate; }
    set { _searchDate = value != null ? value.Value : value; }
}

Solution

  • As has been said, you cannot declare new operators in C#, ever, at all. This is a limitation of the language, the compiler, and the environment.

    What you CAN do is utilize the null coalescing operator or write a few generic Extension Methods to handle what you want, such as

    public static string EmptyIfNull(this string source, string ifValue, string ifNull = "")
    {
        return source != null ? ifValue : ifNull;
    }
    

    and implemented via

    string greeting = name.EmptyIfNull("hello there " + name);