Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with the below Null-Conditional Operator?

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.

like image 506
priyanka.sarkar Avatar asked Mar 10 '15 07:03

priyanka.sarkar


1 Answers

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.

like image 157
i3arnon Avatar answered Sep 30 '22 09:09

i3arnon