What is wrong with
public int Add(int? a, int? b)
{
return (a?.0 + b?.0);
}
Compile Error: Cannot implicitly convert type 'int?' to 'bool'
Just trying to get the flavour of adding two nullable integers in the C#6.0 way.
I know the other ways too(like hasvalue etc.), but I am experimenting with this new operator.
Well, first of all x?.0
doesn't mean anything when x
is an int?
. 0
isn't a property or method on int?
.
It seems as though you were trying to use the null coalescing operator ??
instead of the null conditional operation ?.
. If that's the case your method should look like this:
public int Add(int? a, int? b)
{
return a ?? 0 + b ?? 0;
}
If that's not the case and you meant ?.
then you can test this operator with an extension method to int
that just returns its value:
public static int Identity(this int value)
{
return value;
}
And use it as you tried to originally (but with int?
):
public int? Add(int? a, int? b)
{
return a?.Identity() + b?.Identity();
}
However, if you just want to combine these int?
parameters together you don't need anything new. This just works:
public int? Add(int? a, int? b)
{
return (a + b);
}
Both options will return a result when both parameters aren't null
, otherwise it would return null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With