How to overload Null-conditional operators "?."

Viewed 478

There is a simple class:

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            Test test = null;
            int? t;
            t = test?.i;  // in this place the overloaded method "operator! =" is NOT called
            if (test != null) // in this place the overloaded method "operator! =" is called
            {
                t = test.i;
            }
        }
    }
    public class Test
    {
        public int i = 5;
        public override bool Equals(object obj)
        {
            return true;
        }
        public static bool operator ==(Test test1, Test test2)
        {
            return true;
        }
        public static bool operator !=(Test test1, Test test2)
        {
            return true;
        }
    }
}

In this line:

if (test != null)

called

public static bool operator !=(Test test1, Test test2)

but in this line:

t = test?.i;

none of the overloaded methods are called

How to overload operator "?."

1 Answers

No, you can't overload the Null-conditional operators. See the list of C# Overloadable operators.


Addendum The ability to overload this operator has actually been proposed to the C# language team. See Proposal: Allow null conditional (?.) and null coalescing ()?? operators to be overloaded and Proposal: nullable-like types. These has not been aproved.

What follows is my understanding of the concerns regarding these and similar proposals:

Changing the semantics of these operators could have a lot of ramifications. For example, given that the operators are static, it would be possible to make it say that something that is null is not. Which would mean a lot of problems for a lot of code. On the flip side, you could have code that hangs too long on a reference or not long enough that would bring problems with the garbage collection.

Even if these and similar issues could be solved, it is not a change to be taken lightly. We are talking about a lot of problems for existing code, that is already deployed in production.

Related