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.
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 ( )
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With