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();
Best Answer
From C# 6 onwards, you can just use:
or:
The
?.
is the null-propagating operator, and will cause the.Invoke()
to be short-circuited when the operand isnull
. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.===
Prior to C# 6, no: there is no null-safe magic, with one exception; extension methods - for example:
now this is valid:
In the case of events, this has the advantage of also removing the race-condition, i.e. you don't need a temporary variable. So normally you'd need:
but with:
we can use simply: