Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle null if passed from a calling function to a called function whose parameter is nullable integer?

Tags:

c#

I have been asked a question in the interview

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

null is passed in a's place. how will you handle this?

I said

if (a == null ) { //do something }
else { // do something }

He didnot say anything.

Waiting for the reply.

like image 867
priyanka.sarkar Avatar asked Dec 09 '22 05:12

priyanka.sarkar


2 Answers

As an interviewer I would have expected this:

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

It is called coalescing operator and exists in several languages and is made exactly for that purpose. It has a very low precedence so do not forget the ( )

like image 65
Askolein Avatar answered Dec 10 '22 18:12

Askolein


Whtever you have said its also correct but interviewer might wanted to know how updated you are..

 if(!a.HasValue)
    {
        a = 0;
    }

or shorter is :-

a = a != null ? a : 0;

and one more operator as suggested by Askolein is ?? as shown below :-

a ?? 0;
like image 24
Neel Avatar answered Dec 10 '22 19:12

Neel