Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to overload null-coalescing operator?

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?

like image 797
Patrik Svensson Avatar asked Dec 08 '08 10:12

Patrik Svensson


People also ask

Can I use null-coalescing operator?

Null-coalescing Operator Use this operator to fall back on a given value. In cases where a statement could return null, the null-coalescing operator can be used to ensure a reasonable value gets returned. This code returns the name of an item or the default name if the item is null.

Why we use null-coalescing operator?

operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-hand operand.

Which is null-coalescing operator?

The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.

What is null-coalescing operator in C#?

The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null ; otherwise, it evaluates the right-hand operand and returns its result.


2 Answers

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.

like image 170
Simon Avatar answered Oct 19 '22 07:10

Simon


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
like image 20
Pete OHanlon Avatar answered Oct 19 '22 07:10

Pete OHanlon