Possible to overload null-coalescing operator?

戏子无情 提交于 2019-11-29 05:24:26

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.

Pete OHanlon

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");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!