-3

Can any one tell me the meaning of the below C# code

true? para1:para2;

For example,

char x = 'A';         
Console.WriteLine(true? x : 0);

The console prints 65

I do not understand how it works.

Techie
  • 73
  • 1
  • 9
  • 1
    [Always read the docs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator). – 41686d6564 stands w. Palestine Nov 07 '19 at 11:35
  • 1
    Note that in this particular case, it's quite redundant and not useful at all. It's equivalent to `Console.WriteLine(x);` because `true` is always true. – 41686d6564 stands w. Palestine Nov 07 '19 at 11:36
  • These are not the right answers. Pls tell me what is meant by "true?" – Techie Nov 07 '19 at 11:37
  • 1
    `true?` **allways** returns `true`, so `Console.WriteLine` will allways print `A`. Or in other words: your ternary operator is useless. – MakePeaceGreatAgain Nov 07 '19 at 11:42
  • When I tried to print `Console.WriteLine(x)` it prints "A". And when I declared `x` as `string` it gives `Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'int'` error. I think OP knows how ternary operator works. But how this code works? – DhavalR Nov 07 '19 at 12:06
  • From `https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/char`, "The char type is implicitly convertible to the following integral types: ushort, int, uint, long, and ulong." So in your case `x == 65` is `TRUE`. In ternary operator right is `0` that is integer, and char is implicitly convertible to interger, so it prints `65`. If you write false, it should print `0`; – DhavalR Nov 07 '19 at 12:10

1 Answers1

0

Its a ternary operator

 condition? 'execute this part if condition satisfies':'execute this part if condition not satisfies'

In your example Console.WriteLine(true? x : 0);

if something is true,it writes A(as the value of x is A) else 0

Ajoe
  • 1,397
  • 4
  • 19
  • 48
  • I understand the tertiary operators. I was asking what is meant by 'true?'. Now I understand that true is just always true and that was just added to the code. – Techie Nov 07 '19 at 11:41