Is there an equivalent of SQL NULLIF function built-in within c#?
Example of what it could look like :
double? result
double denominator = 0;
double Numerator = 100;
result = Numerator / NullIf(denominator, 0);
result = Numerator / denominator.NullIf(0);
result = Numerator / Object.NullIf(denominator, 0);
ISNULL( ) function replaces the Null value with placed value. The use of ISNULL ( ) function is very common in different situations such as changing the Null value to some value in Joins, in Select statement etc. NULLIF ( ) function returns us Null if two arguments passed to functions are equal.
NULLIF is equivalent to a searched CASE expression in which the two expressions are equal and the resulting expression is NULL.
The NULLIF() function returns NULL if two expressions are equal, otherwise it returns the first expression.
No, there is no language feature for this at present.
You can easily get the same result, either with a ternary if:
result = Numerator / (denominator == 0 ? (double?)null : denomiantor);
Or even wrapping it as a generic function, so something like:
Nullable<T> NullIf<T>(T left, T right)
{
return left == right ? (T?)null : left;
}
which could then be called like:
result = Numerator / NullIf(denominator, 0);
Accepted answer give me:
Operator '==' cannot be applied to operands of type 'T' and 'T'
My working example of NULLIF:
public static T? NullIf<T>(T left, T right) where T : struct
{
return EqualityComparer<T>.Default.Equals(left, right) ? (T?)null : left;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With