Method call if not null in C#
问题 Is it possible to somehow shorten this statement? if (obj != null) obj.SomeMethod(); because I happen to write this a lot and it gets pretty annoying. The only thing I can think of is to implement Null Object pattern, but that's not what I can do every time and it's certainly not a solution to shorten syntax. And similar problem with events, where public event Func<string> MyEvent; and then invoke if (MyEvent != null) MyEvent.Invoke(); 回答1: From C# 6 onwards, you can just use: MyEvent?.Invoke