Reputation: 2472
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);
Upvotes: 12
Views: 9185
Reputation: 187
Why do we assume this extension method is able to know what is null in our context.
Its the responsibility of the context that calls it. Therefore is a mistake of saying only one value will be considered null as all the response in this thread impliy.
public static T? NullIf<T>(this T value, Func<T,bool> isConsideredNull)
{
if(value == null)
{
return null;
}
return isConsideredNull(value) ? (T?)null : value;
}
We would use it the following way
string test = "NULL";
test.NullIf((x)=> x.Equals("NULL"));
test.NullIf((x)=> x == "NULL");
test.NullIf((x)=> x.Equals("NULL",StringComparison.InvariantCultureIgnoreCase));
Upvotes: 0
Reputation: 571
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;
}
Upvotes: 7
Reputation: 38130
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);
Upvotes: 9
Reputation: 32276
No but you could create one.
public static Nullable<T> NullIf<T>(T first, T second) where T : struct
{
if(first == second)
return new Nullable<T>();
return new Nullable<T>(first);
}
Upvotes: 4
Reputation: 17579
There is no. but you can use ternary operator for compact way of writing it:
double? result
double denominator = 0;
double Numerator = 100;
result = denominator == 0 ? (double?)null : Numerator / denominator;
However there is equivalent of IFNULL:
result = x ?? 0;
equivalent of:
result = x.HasValue? x.Value : 0;
Upvotes: 1