Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of SQL NULLIF function in c#?

Tags:

c#

.net

null

nullif

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);
like image 256
AXMIM Avatar asked Aug 27 '15 15:08

AXMIM


People also ask

What is the difference between Isnull () and Nullif () function?

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.

What is Nullif SQL?

NULLIF is equivalent to a searched CASE expression in which the two expressions are equal and the resulting expression is NULL.

What is the use of Nullif function?

The NULLIF() function returns NULL if two expressions are equal, otherwise it returns the first expression.


Video Answer


2 Answers

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);
like image 52
Rowland Shaw Avatar answered Sep 27 '22 18:09

Rowland Shaw


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;
}
like image 37
BorisSh Avatar answered Sep 27 '22 19:09

BorisSh