I would like a simple, modestly efficient NullIf() generic extension for nullable and non-nullable value types including enums. The trickiness seems to be with equality testing in generics.
Any issues with this working implementation?
/// <summary>
/// Return null if the value is equal to the argument. Applies to value types including enums.
/// </summary>
public static T? NullIf<T>(this T value, T equalsThis)
where T : struct, IComparable // values types (including enum)
{
return Comparer<T>.Default.Compare(value, equalsThis) == 0
? (T?)null
: value;
}
/// <summary>
/// Return null if the value is null or the value is equal to the argument.
/// Applies to value types including enums.
/// </summary>
public static T? NullIf<T>(this T? value, T equalsThis)
where T : struct, IComparable // values types (including enum)
{
return !value.HasValue
? (T?)null
: value.Value.NullIf(equalsThis);
}
Test cases:
int i = 32;
int? i2 = i.NullIf(32); // null
int? i3 = i.NullIf(50); // 32
System.IO.FileAccess fa = System.IO.FileAccess.Read;
System.IO.FileAccess? fa2 = fa.NullIf(System.IO.FileAccess.Read); // null
System.IO.FileAccess? fa3 = fa.NullIf(System.IO.FileAccess.ReadWrite); // Read
References: Comparer<T>.Default
nulls. But I guess you have such a case, haven't you? \$\endgroup\$