Search code examples
c#.netnullnullif

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


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);

Solution

  • 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);