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.
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;
As an interviewer, I would expect this:
public int Add(int? a, int? b) { return (a ?? 0) + (b ?? 0); }
. , ( )
( )
, , ,
public int Add(int? a, int? b) { a = a!= null ? a : 0; b = b!= null ? b : 0; return a+b; }
- , , 0 null
null
. , -
public int? Add(int? a, int? b)
: null null. , ; , null, 0, a ?? 0 . , , (a + b) ?? 0, 0, null.
0
a ?? 0
(a + b) ?? 0
, , , , , . : " , , ββ null s?"
GetValueOrDefault Nullable<T>, T, int, null.
GetValueOrDefault
Nullable<T>
T
int
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; }
Null-Conditional Operator (# 6.0)
return (a?. + b?.);
return (a + b);