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?)
As extension methods are in reality static methods of another class, they work even if the reference is null .
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.
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.
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.
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.
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