Possible pitfalls of using this (extension method based) shorthand

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

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-11-27 20:30

    it does make the code a little easier to read, but at the cost of extending object. This would appear on everything,

    Note that you are not actually extending anything (except theoretically).

    propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0);
    

    will generate IL code exactly as if it were written:

    ExtentionClass::IfNotNull(myObject2,  x => x.IntProperty, 0);
    

    There is no "overhead" added to the objects to support this.

    0 讨论(0)
  • 2020-11-27 20:32

    Personally, even after all your explanation, I can't remember how the heck this works:

    if( obj1.NullCompare( obj2, (x,y) => x.Property == y.Property ) 
    

    This could be because I have no C# experience; however, I could read and understand everything else in your code. I prefer to keep code language agnostic (esp. for trivial things) so that tomorrow, another developer could change it to a whole new language without too much information about the existing language.

    0 讨论(0)
  • 2020-11-27 20:32

    Here is another solution using myObject.NullSafe(x=>x.SomeProperty.NullSafe(x=>x.SomeMethod)), explained at http://www.epitka.blogspot.com/

    0 讨论(0)
提交回复
热议问题