What happened to the Null-Conditional Operator below?

What is wrong with

public int Add(int? a, int? b) { return (a?.0 + b?.0); } 

Compilation error: Unable to implicitly convert type 'int?' to 'bool'

Just trying to get the flavor of adding two zero integers in a C # 6.0 path.

I know other ways (e.g. hasvalue, etc.), but I'm experimenting with this new operator.

+5
source share
1 answer

Well, first of all x?.0 doesn't mean anything if x is int? . 0 not a property or method on int? .

It seems you tried to use the zero coalescing operator ?? instead of zero conditional operation ?. . If in this case your method should look like this:

 public int Add(int? a, int? b) { return a ?? 0 + b ?? 0; } 

If it is not, and you mean ?. , then you can test this statement using the extension method to int , which simply returns its value:

 public static int Identity(this int value) { return value; } 

And use it as you tried initially (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 int? You do not need anything new. It works:

 public int? Add(int? a, int? b) { return (a + b); } 

Both parameters will return the result when both parameters are not null , otherwise it will return null .

+11
source

Source: https://habr.com/ru/post/1215033/


All Articles