The c# null-conditional operator and extension methods

Using the null-conditional operator can break existing code calling extension methods. In this post I’ll explain how this can happen.

Since C# 6 we can use the null-conditional operator in our code to prevent NullReferenceExceptions like this:

So no NullReferenceException is thrown on line 4 and the result of the whole expression becomes NULL. Therefore, the output of this program will be “NULL”.

Now let’s try something else:

The main difference is that the methodcall on line 4 is an own custom extension method and being an extension method, it can handle the NULL-case itself, which an instance method can never do:

Well, this also produces “NULL” as output. This is exactly what we would expect, or, isn’t it? The “test” variable contains a NULL value so the extension method is never called, but as you can see in the implementation of this extension method, it explicitly handles the case where the instance is null (whether this is good or bad design is irrelevant at this point Glimlach). Of course, this will never happen as long as we use the null-conditional operator.

Is this strange? I don’t think so, I think it’s the right decision to make the null-conditional operator work consistently across normal instance methods and extension methods. If you want to let the extension method handle the NULL-case itself, just don’t use the null-conditional operator.

Moral of this story: Don’t go around and sprinkle the null-conditional operator around in your existing code without thinking about whether the method you are calling is an extension method (and thus in fact a static method) which already handles the NULL-case itself, because this might break something unexpected in your program.

Tweet about this on TwitterShare on LinkedIn

Reacties

Het e-mailadres wordt niet gepubliceerd.

*