Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
Is it possible to simplify the below condition using the null-coalescing operator or any other simplified code?
int? c,a,b; if(a!=null) { c = a; } else if(b!=null) { c = b; } else { c = null; }
Thanks in Advance
c = a ?? b
int
int c = a ?? b ?? default(int);
0
null
int? c = a ?? b;
c
You mean something like:
int? c = a ?? (b ?? null)
Note that according to your if-else statement, c has to be int? type. For the same reason, it makes sense both a and b are of int? type.
int?
a
b
Hence, as b may be null, the same expression can be rewritten as:
Add a comment
c = a ?? b ?? null;
Although if your catch is null anyways then you only really need
c = a ?? b;
Edit: As other users have stated it's important that your int is nullable (int?) if you're working with them.
Assuming that they are all of Type int?
int? c = a ?? b; //no need for an explicit null. If b is null so will c be.
because the question doesn't make sense if they are of Type int.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
c = a ?? bwould do it. Butintisn't nullable so I'm not sure what is going on in your example.int c = a ?? b ?? default(int);is probably what you're looking for, assuming you're okay with0instead ofnull, or justint? c = a ?? b;if you wantcto be nullable.