Method call if not null in C#

后端 未结 11 1108
情深已故
情深已故 2020-12-12 13:05

Is it possible to somehow shorten this statement?

if (obj != null)
    obj.SomeMethod();

because I happen to write this a lot and it gets p

11条回答
  •  Happy的楠姐
    2020-12-12 13:39

    I have made this generic extension that I use.

    public static class ObjectExtensions {
        public static void With(this T value, Action todo) {
            if (value != null) todo(value);
        }
    }
    

    Then I use it like below.

    string myString = null;
    myString.With((value) => Console.WriteLine(value)); // writes nothing
    myString = "my value";
    myString.With((value) => Console.WriteLine(value)); // Writes `my value`
    

提交回复
热议问题