views:

541

answers:

4

Is it possible to override 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?

Of course there is no real need for this (at least I think so) - so before you answer "why would you want to do that" - I am just curious if it's possible.

+4  A: 

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.

Mehrdad Afshari
Also a good answer. Thank you!
Patrik
+10  A: 

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.

Simon
Good answer. Thank you very much!
Patrik
+6  A: 

According to ECMA-334, is is not possible to overload the ?? operator. Similarly, you cannot overload the following operators:

  • =
  • &&
  • ||
  • ?:
  • checked
  • unchecked
  • new
  • typeof
  • as
  • is
Pete OHanlon
A: 

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

return instance.MyValue != null ? instance : new MyClass("Default");
soniiic
-1: you are missing the point, you can already do what you propose with OP's code... also please read the question carefully, he is not asking how to do that but if it is possible to overload the null-coalescing operator - which, unfortunately, is not.
ANeves
I understand he was asking about overloading the ?? operator and I read the responses saying it was impossible. Therefore I was just providing a solution which does work with the expected result (granted it doesn't use the ?? operator) for anyone who might come across this page looking for something that works.
soniiic