public static short? ToShortNullable(this bool? b)
{
return b.HasValue ? null : (b.Value==true : 1 ? 0);
}
I have tried the above but the syntax is not happy, I want to return null
if b is null
, 1
if b is true
and 0
if b is false
.
CodePudding user response:
You have two problems: one is that you have the syntax back to front with the :
and ?
in b.Value==true : 1 ? 0
and the other is that you have the logic back to front. You're trying to return null when b
does have a value and trying to extract a value from b
when it doesn't have one.
Try this:
public static short? ToShortNullable(this bool? b)
{
return b.HasValue ? (b.Value==true ? 1 : 0) : null;
}
And since b.Value == true
is the same as b.Value
you can simplify to:
public static short? ToShortNullable(this bool? b)
{
return b.HasValue ? (b.Value ? 1 : 0) : null;
}
CodePudding user response:
If you want to make it modern and fancy:
public static short? ToShortNullable(this bool? b) => b switch
{
true => 1,
false => 0,
_ => null
};
See it in action in this fiddle
CodePudding user response:
return !b.HasValue ? null : (short)(b.Value ? 1 : 0);
CodePudding user response:
try this
public static short? ToShortNullable(this bool? b)
{
return b == null ? null : b == true ? 1 : (short?) 0 ;
}