4

Why is this code not valid? Pretty sure it's legit in C /C++

Pseudocode:

String s = Console.ReadLine();
int x = 0;
Int32.TryParse(s, out x) ? Console.WriteLine("Foo") :  Console.WriteLine("bar");
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
aCuria
  • 6,935
  • 14
  • 53
  • 89
  • 1
    Perhaps you mean `Console.WriteLine` instead of `Console.writeline`. – Codor Jul 19 '16 at 06:27
  • It's pseudo code. I'm typing this out on mobile. The question is about the ternary operator, the code will compile fine as an if-else – aCuria Jul 19 '16 at 06:30
  • @Hank sorry about that, I thought the question was simple enough that it could be answered without having to compile it. I don't recall posting any error messages though – aCuria Jul 19 '16 at 06:51

3 Answers3

5

The ternary operator is used to return values and those values must be assigned.

If you want to invoke void methods in a ternary operator, you can use delegates like this:

String s = Console.ReadLine();
int x = 0;
(Int32.TryParse(s, out x) ? new Action(() => Console.WriteLine("Foo")) : () => Console.WriteLine("bar"))();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
1

console.writeline return void.. The conditional operator (?:) returns one of two values depending on the value of a Boolean expression

MSDN

marius
  • 319
  • 1
  • 9
0

As discussed here, in C#, not every expression can be used as a statement.

Community
  • 1
  • 1
Codor
  • 17,447
  • 9
  • 29
  • 56