Question

Is it possible to overload the null-coalescing operator for a class in C#?

Say for example I want to return a default value if an instance is null and return the instance if it's not. The code would look like something like this:

   return instance ?? new MyClass("Default");  

But what if I would like to use the null-coalescing operator to also check if the MyClass.MyValue is set?

Was it helpful?

Solution

Good question! It's not listed one way or another in the list of overloadable and non-overloadable operators and nothing's mentioned on the operator's page.

So I tried the following:

public class TestClass
{
    public static TestClass operator ??(TestClass  test1, TestClass test2)
    {
        return test1;
    }
}

and I get the error "Overloadable binary operator expected". So I'd say the answer is, as of .NET 3.5, a no.

OTHER TIPS

According to the ECMA-334 standard, it is not possible to overload the ?? operator.

Similarly, you cannot overload the following operators:

  • =
  • &&
  • ||
  • ?:
  • ?.
  • checked
  • unchecked
  • new
  • typeof
  • as
  • is

Simple answer: No

C# design principles do not allow operator overloading that change semantics of the language. Therefore complex operators such as compound assignment, ternary operator and ... can not be overloaded.

This is rumored to be part of the next version of C#. From http://damieng.com/blog/2013/12/09/probable-c-6-0-features-illustrated

7. Monadic null checking

Removes the need to check for nulls before accessing properties or methods. Known as the Safe Navigation Operator in Groovy).

Before

if (points != null) {
    var next = points.FirstOrDefault();
    if (next != null && next.X != null) return next.X;
}   
return -1;

After

var bestValue = points?.FirstOrDefault()?.X ?? -1;

If anyone is here looking for a solution, the closest example would be to do this

return instance.MyValue != null ? instance : new MyClass("Default");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top