0

This:

int? temp = 0;
return "123 " + temp ?? "null" + " 456";

returns 123 0, but I expected: 123 0 456

This:

int? temp = null;
return "123 " + temp ?? "null" + " 456";

returns 123 , but I expected: 123 null 456

How can I get expected results?

dafie
  • 951
  • 7
  • 25
  • 2
    `return "123 " + (temp ?? "null") + " 456";`, please note `(...)`. Your current code does `return "123 " + temp ?? ("null" + " 456");` – Dmitry Bychenko Aug 27 '20 at 10:25
  • @DmitryBychenko that doesnt compile – adjan Aug 27 '20 at 10:26
  • 1
    Does this answer your question? [What is the operator precedence of C# null-coalescing (??) operator?](https://stackoverflow.com/questions/511093/what-is-the-operator-precedence-of-c-sharp-null-coalescing-operator) – GSerg Aug 27 '20 at 10:26

4 Answers4

0

You need to change the precedence of the ?? operator. Use

return "123 " + (temp?.ToString() ?? "null") + " 456";
adjan
  • 13,371
  • 2
  • 31
  • 48
0

Your current code does

  int? temp = 0;
  return "123 " + temp ?? ("null" + " 456");

Put it in different order:

  int? temp = 0;
  return "123 " + (temp?.ToString() ?? "null") + " 456";

Or, in order to get rid of pesky +:

  return $"123 {temp?.ToString() ?? "null"} 456";
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

So many fancy solutions here already, I'll add a simple "old stylish one" :)

"123 " + (temp.HasValue ? temp.ToString() : "null") + " 456"
Esko
  • 4,109
  • 2
  • 22
  • 37
0

This is one way of writing it that should work:

$"123 {(temp == null ? "null" : temp.ToString())} 456"
Petter
  • 321
  • 3
  • 9