Search code examples
c#.netoperator-overloadingnull-coalescing-operator

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?


Solution

  • 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.