Possible pitfalls of using this (extension method based) shorthand

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

    While extension methods generally cause misunderstandings when called from null instances, I think the intent is pretty straightforward in this case.

    string x = null;
    int len = x.IfNotNull(y => y.Length, 0);
    

    I would want to be sure this static method works on Value Types that can be null, such as int?

    Edit: compiler says that neither of these are valid:

        public void Test()
        {
            int? x = null;
            int a = x.IfNotNull(z => z.Value + 1, 3);
            int b = x.IfNotNull(z => z.Value + 1);
        }
    

    Other than that, go for it.

提交回复
热议问题