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?
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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With