Currently there is no such an operator. But in C# 6 "safe-navigation" operator will appear and you'll be able to write
int number = sampleClass?.Number;
This code won't fail with NullRef even if sampleClass
equals null
. For now you can use the following extension method that extracts value from an object and encapsulates null-check:
public static TResult Maybe<TSource, TResult>(
this TSource source, Func<TSource, TResult> produceResult, Func<TResult> produceDefault)
where TSource : class
{
return source == null ? produceDefault() : produceResult(source);
}
and use it as follows:
int numberOrFive = sampleClass.Maybe(c => c.Number, () => 5);