How to handle null if it is passed from the calling function to the called function whose parameter is NULL integer?

I was asked a question in an interview

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

null is passed in place. how do you handle this?

I said

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

He said nothing.

The reply is in process.

+4
source share
6 answers

If you said that this is also correct, but the interviewer may want to know how updated you are.

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

or shorter: -

a = a != null ? a : 0;

and another operator proposed by Ascolin, as shown below: -

a ?? 0;
+4
source

As an interviewer, I would expect this:

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

. , ( )

+5

, , ,

public int Add(int? a, int? b)
{
    a = a!= null ? a : 0;
    b = b!= null ? b : 0;
    return a+b;
}

- , , 0 null

+2

. , -

public int? Add(int? a, int? b)

: null null. , ; , null, 0, a ?? 0 . , , (a + b) ?? 0, 0, null.

, , , , , . : " , , ​​ null s?"

+2

GetValueOrDefault Nullable<T>, T, int, null.

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

, , ,

public int Add(int? a, int? b)
{
    if(!a.HasValue)
        throw new ArgumentNullException("a");
    if(!b.HasValue)
        throw new ArgumentNullException("b");
    return a.Value + b.Value;
}
+1

Null-Conditional Operator (# 6.0)

return (a?. + b?.);

return (a + b);

0

All Articles