Operator?. and extension methods

Extension methods with operator . always called, even if the object is null without throwing a NullReferenceException . Using the ?. He is never called. For instance:

 using System; public class Program { public static void Main() { A a = null; ab(); // 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 is the extension method not called in this case? Is this a feature of ambiguos?

+5
source share
1 answer

Your expression is a? .B (), which uses the ? Operator . translates to the equivalent:

 if(a != null) { ab(); } 

therefore therefore your method is not called.

+15
source

Source: https://habr.com/ru/post/1239478/


All Articles