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();
What you're looking for is the Null Conditional (not "coalescing") operator:
?.
. It's available as of C# 6.Your example would be
obj?.SomeMethod();
. If obj is null, nothing happens. When the method has arguments, e.g.obj?.SomeMethod(new Foo(), GetBar());
the arguments are not evaluated ifobj
is null, which matters if evaluating the arguments would have side effects.And chaining is possible:
myObject?.Items?[0]?.DoSomething()
Maybe not better but in my opinion more readable is to create an extension method
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:
Yes, in C# 6.0 -- https://msdn.microsoft.com/en-us/magazine/dn802602.aspx.
I agree with the answer by Kenny Eliasson. Go with Extension methods. Here is a brief overview of extension methods and your required IfNotNull method.
Extension Methods ( IfNotNull method )
This article by Ian Griffiths gives two different solutions to the problem that he concludes are neat tricks that you should not use.