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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With