Konstantin Zadiran
Konstantin Zadiran

Reputation: 1541

Operator ?. and extension methods

Extension methods with . operator always called, even if object is null without throwing NullReferenceException. By using operator ?. it will never called. For example:

using System;

public class Program
{
    public static void Main()
    {
        A a = null;
        a.b(); // works
        a?.b(); // doesn't work
    }
}

public class A { }

public static class ext
{
    public static void b(this A a)
    {
        Console.WriteLine("I'm called");
    }
}

Why extension method isn't called in this case? Is this an ambiguos feature?

Upvotes: 5

Views: 598

Answers (2)

Marcel Greter
Marcel Greter

Reputation: 275

Calling an extension method has the following edge-case: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#11893-extension-method-invocations

Note: Unlike an instance method invocation, no exception is thrown when expr evaluates to a null reference. Instead, this null value is passed to the extension method as it would be via a regular static method invocation. It is up to the extension method implementation to decide how to respond to such a call.

This explains why your compiler will make a.b() work (it emits a call IL op). And it's probably save to assume that the a?.b() will actually include a runtime null check, thus not executing the method.

Upvotes: 1

Marcin Zablocki
Marcin Zablocki

Reputation: 10693

Your expression a?.b() which uses ?. operator translates to equivalent:

if(a != null)
{
  a.b();
}

so this is why your method does not get called.

Upvotes: 16

Related Questions