Possible to overload null-coalescing operator?
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.
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;