Why can't we write Console.Writeline() in if condition in C#
? But we can write
printf() statement in if condition in C
?
In C, the return type of printf
is int
- the number of characters written.
Also in C, an if
condition can be any non-void data type, basically.
Compare that with C# and .NET, where Console.WriteLine
has a return type of void
, and the condition in an if
statement must have a type of bool
(or be implicitly convertible to bool
). (So even if Console.WriteLine
returned int
, you'd still need something like if (Console.WriteLine(...) != 0)
in order to make it valid.)
What do you want the condition to actually check? If Console.WriteLine
fails for some reason, it'll throw an exception anyway...
See more on this question at Stackoverflow