0

Is this possible in one line of code ? null : yourHelpfulAnswer

Thank you in advance.

var x = await Foo_Get() == null ? 123: Foo.SomeProperty;

Just seems like there is a much better way than:

var myVal = 123;
var foo = await Foo_Get();
if(foo != null) myVal = foo.SomeProperty;
Vert
  • 83
  • 1
  • 6
  • Don't you already have it on one line? – sanitizedUser May 22 '20 at 18:08
  • I recommend you take a look into: https://stackoverflow.com/questions/446835/what-do-two-question-marks-together-mean-in-c – Isaí Hinojos May 22 '20 at 18:08
  • var x = await Foo_Get() == null ? 123: Foo.SomeProperty; is not functioning, just pseudocode of what I am trying to accomplish. – Vert May 22 '20 at 18:10
  • Just for fun, I would suggest you check out the "Null-Object" pattern. That might/might not work for you. I know the pattern gets a lot of flack for generating to much overhead. But really, you might disagree. – Morten Bork May 22 '20 at 18:10
  • I think everything looks good just make sure that Foo_Get() is async Task<> function – Wowo Ot May 22 '20 at 18:11

2 Answers2

4

That should do the trick:

var myVal = (await Foo_Get())?.SomeProperty ?? 123;

Simplified:
? = if value on left is null use null, otherwise use property
?? = if value on the left is null use the value on the right instead.

Vincent
  • 482
  • 4
  • 15
  • Thank you! Tested and works. So quick I can't even mark as the answer for 5 more minutes. – Vert May 22 '20 at 18:15
0

You can use the null coalescing operator to set myVal:

var myVal = (await Foo_Get())?.SomeProperty ?? 123;
NetMage
  • 26,163
  • 3
  • 34
  • 55