I love the null-coalescing operator because it makes it easy to assign a default value for nullable types.
int y = x ?? -1;
That\'s great,
We use a method called NullOr.
// Call ToString() if it’s not null, otherwise return null
var str = myObj.NullOr(obj => obj.ToString());
// Supply default value for when it’s null
var str = myObj.NullOr(obj => obj.ToString()) ?? "none";
// Works with nullable return values, too —
// this is properly typed as “int?” (nullable int)
// even if “Count” is just int
var count = myCollection.NullOr(coll => coll.Count);
// Works with nullable input types, too
int? unsure = 47;
var sure = unsure.NullOr(i => i.ToString());
/// Provides a function delegate that accepts only value types as return types.
/// This type was introduced to make
/// work without clashing with .
public delegate TResult FuncStruct(TInput input) where TResult : struct;
/// Provides a function delegate that accepts only reference types as return types.
/// This type was introduced to make
/// work without clashing with .
public delegate TResult FuncClass(TInput input) where TResult : class;
/// Provides extension methods that apply to all types.
public static class ObjectExtensions
{
/// Returns null if the input is null, otherwise the result of the specified lambda when applied to the input.
/// Type of the input value.
/// Type of the result from the lambda.
/// Input value to check for null.
/// Function to apply the input value to if it is not null.
public static TResult NullOr(this TInput input, FuncClass lambda) where TResult : class
{
return input == null ? null : lambda(input);
}
/// Returns null if the input is null, otherwise the result of the specified lambda when applied to the input.
/// Type of the input value.
/// Type of the result from the lambda.
/// Input value to check for null.
/// Function to apply the input value to if it is not null.
public static TResult? NullOr(this TInput input, Func lambda) where TResult : struct
{
return input == null ? null : lambda(input);
}
/// Returns null if the input is null, otherwise the result of the specified lambda when applied to the input.
/// Type of the input value.
/// Type of the result from the lambda.
/// Input value to check for null.
/// Function to apply the input value to if it is not null.
public static TResult? NullOr(this TInput input, FuncStruct lambda) where TResult : struct
{
return input == null ? null : lambda(input).Nullable();
}
}