Search code examples
c#operator-keywordternary

Using C# Ternary Operator


Probably a simple syntax problem. This is an attempt at a console program that reads the length of a string that is received via user input. If the length is greater than 144, the user is notified that the string length is too long, otherwise the string inputted is just output to the console.

string input = Console.ReadLine();
(input.Length > 144) ? Console.WriteLine("The message is too long"); : Console.WriteLine(input);
Console.ReadLine();

Getting syntax errors in the present state on line 2. Am I missing parentheses?


Solution

  • try:

    Console.WriteLine((input.Length > 144) ? "The message is too long" : input);
    

    you need to use the return value of the operator, or receive a compile-time error Only assignment, call, increment, decrement, and new object expressions can be used as a statement.

    None of these other answers will compile, I'm not sure what everyone is getting at.