Best syntax for a = (x == null) ? null : x.func()

后端 未结 7 811
囚心锁ツ
囚心锁ツ 2020-12-24 04:50

Basic question here - I have many lines of code that look something like:

var a = (long_expression == null) ? null : long_expression.Method();
7条回答
  •  -上瘾入骨i
    2020-12-24 05:34

    Well, you could use an extension method like this:

    public static TResult NullOr(this TSource source,
        Func func) where TSource : class where TResult : class
    {
        return source == null ? null : func(source);
    }
    

    Then:

    var a = some_long_expression.NullOr(x => x.Method());
    

    Or (depending on your version of C#)

    var a = some_long_expression.NullOr(Foo.Method);
    

    where Foo is the type of some_long_expression.

    I don't think I would do this though. I'd just use the two line version. It's simpler and less clever - and while "clever" is fun for Stack Overflow, it's not usually a good idea for real code.

提交回复
热议问题