priyanka.sarkar
priyanka.sarkar

Reputation: 26498

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

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.

Upvotes: 4

Views: 110

Answers (6)

priyanka.sarkar
priyanka.sarkar

Reputation: 26498

Today I learnt about Null-Conditional Operator ( C# 6.0 )

return (a?. + b?.);

also return (a + b); works fine

Upvotes: 0

Neel
Neel

Reputation: 11731

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;

Upvotes: 4

juharr
juharr

Reputation: 32266

Another solution is to use the GetValueOrDefault method of Nullable<T> which will substitute the default value of T, which is zero for int, if it is null.

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

But really you should have asked what the interviewer wanted the method to do with nulls as this could also have been valid

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;
}

Upvotes: 1

Jeroen Mostert
Jeroen Mostert

Reputation: 28779

It's not a very good question. The code as presented doesn't compile, and the shortest possible fix is actually to change the function signature to

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

Addition is supported on nullable integers through lifting: adding null to another value will just yield null. This is almost certainly not what the interviewer was angling for; probably they intended you to treat null as if it was 0, for which a ?? 0 suffices. But maybe they wanted (a + b) ?? 0 instead, which returns 0 if either operand is null.

Well, on second thought, maybe it is a good question, to see if you would ask follow-up questions. The most pertinent one would be: "what do you want this function to do when presented with nulls?"

Upvotes: 2

Askolein
Askolein

Reputation: 3378

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 ( )

Upvotes: 5

No Idea For Name
No Idea For Name

Reputation: 11577

he probably wanted it to be

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

or something of the sort, meaning you place 0 instead of null

Upvotes: 2

Related Questions