Is there any way to perform a sort of null coalesce on a property in C#?
c#, null-coalescing-operator, syntax
Solution
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);
Problem
I'm not quite sure how to phrase this question but the scenario is as follows: Say I have the following class: ``` public class SampleClass { public int Number { get; set; } } ``` I know you can null coalesce the containing class: ``` SampleClass newSampleClass = possibleNullSampleClass ?? notNullSampleClass; ``` Is there any way to perform a sort of null coalesce on the property so I don't have to do this: ``` int? num = sampleClass != null ? new int?(sampleClass.Number) : 5; ``` It seems like it would be very useful to have something like a `???` operator to perform this check so I could do: ``` int? num = sampleClass.Number ??? 5; ``` Is anything like that possible in C#?