Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null propagation operator and extension methods

Tags:

c#

roslyn

c#-6.0

I've been looking at Visual Studio 14 CTP along with C# 6.0 and playing with the null-propagation operator.

However, I couldn't find why the following code does not compile. The features are not yet documented so I'm not sure whether this is a bug or extension methods simply are not supported with the ?. operator and the error message is misleading.

class C {     public object Get()     {         return null;     } }  class CC { }  static class CCExtensions {     public static object Get(this CC c)     {         return null;     } }  class Program {     static void Main(string[] args)     {         C c = null;         var cr = c?.Get();   //this compiles (Get is instance method)          CC cc = null;         var ccr = cc?.Get(); //this doesn't compile          Console.ReadLine();     } } 

Error message is:

'ConsoleApplication1.CC' does not contain a definition for 'Get' and no extension method 'Get' accepting a first argument of type 'ConsoleApplication1.CC' could be found (are you missing a using directive or an assembly reference?)

like image 793
nan Avatar asked Jun 10 '14 18:06

nan


People also ask

Can you call extension method on null?

As extension methods are in reality static methods of another class, they work even if the reference is null .

What is null propagation?

Starting from version 6.0, C# supports a shorter notation, the null conditional operator. It allows checking one or more expressions for null in a call chain, which is called null propagation. Such a notation can be written in a single line whereas a number of if-else statements typically occupy many lines.

What is extension method with example?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What is AC extension method?

A C# extension methods allows developers to extend functionality of an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. C# extension method is a special kind of static method that is called as if it was an instance methods on the extended type.


1 Answers

Yes. This is a bug. Thanks for bringing this up. The sample is supposed to compile and should result in a conditional invocation of Get regardless if Get is an extension or not.

Usage of "?." in cc?.Get() is an indication that caller wants cc null-checked before proceeding further. Even if Get could handle null somehow, caller does not want that to happen.

like image 132
VSadov Avatar answered Oct 05 '22 23:10

VSadov