Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator ?. and extension methods

Tags:

c#

c#-6.0

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?

like image 741
Konstantin Zadiran Avatar asked Dec 30 '15 10:12

Konstantin Zadiran


1 Answers

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.

like image 128
Marcin Zablocki Avatar answered Oct 20 '22 23:10

Marcin Zablocki