1

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

4
  • 9
    Normally c = a ?? b would do it. But int isn't nullable so I'm not sure what is going on in your example. Commented Jul 26, 2018 at 18:04
  • I was just going to say what John did. Commented Jul 26, 2018 at 18:04
  • int c = a ?? b ?? default(int); is probably what you're looking for, assuming you're okay with 0 instead of null, or just int? c = a ?? b; if you want c to be nullable. Commented Jul 26, 2018 at 18:07
  • Sorry I forgot to mention c is a nullable integer. I have updated now Commented Jul 27, 2018 at 6:01

3 Answers 3

4

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.

Hence, as b may be null, the same expression can be rewritten as:

int? c = a ?? b;
Sign up to request clarification or add additional context in comments.

Comments

3
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.

Comments

3

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.

Comments

Your Answer

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.

Ask question

Explore related questions

See similar questions with these tags.