What does a question mark in C # mean? For example here

get { return name != null ? name : "NA"; } 

and is it still possible to use it?

  • five
    Well, this is a ternary operator: '( - Aleksey Shimansky
  • Thanks for the title, otherwise I didn’t even know how to google it ... - Denisok
  • @ Alexey Shimansky, but do not tell me why they use backup storage? class Person { private string name; // the name field public string Name // the Name property { get { return name; } set { name = value; } } } class Person { private string name; // the name field public string Name // the Name property { get { return name; } set { name = value; } } } - Denisok
  • @Denisok wanted so because. Only this is called not so. - Pavel Mayorov 2:32 pm
  • one
    Ternary is any operator with three operands. The operator in question is called the "conditional operator." - VladD 5:58 pm

2 answers 2

The conditional operator (?:) (also known as the ternary operator ) returns one of two values ​​depending on the value of the logical expression. The conditional statement uses the following syntax

 condition ? first_expression : second_expression; 

The condition parameter must be true or false . If the condition parameter is true , the expression first_expression is evaluated and the result of this calculation becomes the result.

If the condition parameter is false , the expression second_expression is evaluated and the result of this calculation becomes the result.

In any case, only one of the two expressions is calculated. The first_expression and second_expression parameters must be of the same type, or an implicit conversion from one type to another must exist.

Calculations, which in another case would require the refinement of the if-else construction , can be expressed using a conditional operator. For example, in the following code, the if operator is first used, and then the conditional operator to notify whether the number entered by the user is five or not:

 int input = Convert.ToInt32(Console.ReadLine()); string classify; // Обычная конструкция if-else. if (input == 5) classify = "Вы ввели число 5! Молодец!"; else classify = "Это НЕ число 5! Это бяка!"; // ?: оператор. classify = (input == 5) ? "Вы ввели число 5! Молодец!" : "Это НЕ число 5! Это бяка!"; 

_A source_

     if(name != null) return name; else return "NA"; 

    ? means if

    : means otherwise

    • Thank you ...) - Denisok