In javascript I can do this
var value = obj.A || 3;
which means, if obj.A
is null or undefined or empty, then use 3 instead.
How can I do that in c#? Or is this the best way in c#?
int value = obj.A == null ? 3 : obj.A;
In javascript I can do this
var value = obj.A || 3;
which means, if obj.A
is null or undefined or empty, then use 3 instead.
How can I do that in c#? Or is this the best way in c#?
int value = obj.A == null ? 3 : obj.A;
You can do this using null propagation ?.
and the null coalescing operator ??
.
var value = obj?.A ?? 3;
The first one says "if obj is null, ignore A and just use null". The second one says "if the left-hand side is null, use the right hand side"
... if obj.A is null or undefined or empty, then use 3 instead.
c# has no concept of undefined
. There is not much you can do about this, if you want an equivalent you would have to create some sort of generic type wrapper but I would advise against it.
There is also no native truthy
check (which is what you are actually referring to when you wrote "empty") in c# like there is in javascript. You would have to build your own method or extension method or add an additional check against the default value in comparison that you want to do.
class Temp
{
public int? A {get;set;}
}
public static void Main()
{
Temp obj = new Temp();
int resultingValue1 = (obj.A == null || obj.A == default(int)) ? 3 : (int) obj.A;
// or
int resultingValue2 = obj.A.IsNullEmpty() ? 3 : (int) obj.A;
}
public static class Extensions
{
public static bool IsNullEmpty<T>(this T valueToCheck)
{
return valueToCheck == null || EqualityComparer<T>.Default.Equals(valueToCheck, default(T));
}
}
See also Marc Gravell's answer Null or default comparison of generic argument in C#