Possible pitfalls of using this (extension method based) shorthand

后端 未结 11 1437
孤独总比滥情好
孤独总比滥情好 2020-11-27 20:00

C#6 Update

In C#6 ?. is now a language feature:

// C#1-5
propertyValue1 = myObject != null ? myObject.StringProperty : null; 

// C#         


        
11条回答
  •  温柔的废话
    2020-11-27 20:11

    We independently came up with the exact same extension method name and implementation: Null-propagating extension method. So we don't think it's confusing or an abuse of extension methods.

    I would write your "multiple levels" example with chaining as follows:

    propertyValue1 = myObject.IfNotNull(o => o.ObjectProp).IfNotNull(p => p.StringProperty);
    

    There's a now-closed bug on Microsoft Connect that proposed "?." as a new C# operator that would perform this null propagation. Mads Torgersen (from the C# language team) briefly explained why they won't implement it.

提交回复
热议问题