Possible pitfalls of using this (extension method based) shorthand

后端 未结 11 1431
孤独总比滥情好
孤独总比滥情好 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条回答
  •  -上瘾入骨i
    2020-11-27 20:30

    I just have to say that I love this hack!

    I hadn't realized that extension methods don't imply a null check, but it totally makes sense. As James pointed out, The extension method call itself is not any more expensive than a normal method, however if you are doing a ton of this, then it does make sense to follow the Null Object Pattern, that ljorquera suggested. Or to use a null object and ?? together.

    class Class1
    {
        public static readonly Class1 Empty = new Class1();
    .
    .
    x = (obj1 ?? Class1.Empty).X;
    

提交回复
热议问题