Possible pitfalls of using this (extension method based) shorthand

后端 未结 11 1438
孤独总比滥情好
孤独总比滥情好 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:23

    How is

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

    easier to read and write than

    if(myObject != null && myObject.ObjectProp != null)
        propertyValue1 = myObject.ObjectProp.StringProperty;
    

    Jafar Husain posted a sample of using Expression Trees to check for null in a chain, Runtime macros in C# 3.

    This obviously has performance implications though. Now if only we had a way to do this at compile time.

提交回复
热议问题