HI WELCOME TO KANSIRIS

The ternary operator (?:) in C#

Leave a Comment

 The ternary operator (?:) in C# is a concise shorthand for an if-else statement

. It is officially called the conditional operator and is the only C# operator that takes three operands.
Syntax
csharp
condition ? expression_if_true : expression_if_false;
Use code with caution.
  • Condition: A Boolean expression that evaluates to true or false.
  • ?: Separates the condition from the "true" result.
  • :: Separates the "true" result from the "false" result.
Basic Example
Instead of writing a multi-line if-else block to assign a value, you can do it in a single line:
csharp
int time = 20;

// Traditional if-else
string result;
if (time < 18) {
    result = "Good day.";
} else {
    result = "Good evening.";
}

// Equivalent ternary operator
string shortResult = (time < 18) ? "Good day." : "Good evening.";

Console.WriteLine(shortResult); // Output: Good evening.
Use code with caution.
Advanced Usage
  1. Nested Ternary: You can chain operators to handle multiple conditions (similar to else if), though this can reduce readability if overused.
    csharp
    int score = 85;
    string grade = score >= 90 ? "A" : (score >= 80 ? "B" : "C");
    // Result: "B"
    
    Use code with caution.
  2. Conditional Ref: Since C# 7.2, you can use the ternary operator to return a reference to a variable rather than just its value.
    csharp
    var array = new int[] { 1, 2, 3 };
    ref int target = ref (condition ? ref array[0] : ref array[1]);
    
    Use code with caution.
  3. Method Calls: You can use ternary operators to decide which method to execute, provided both methods return the same type.
    csharp
    string message = IsUserLogged() ? GetWelcomeMessage() : GetLoginPrompt();
    
    Use code with caution.
Best Practices
  • Keep it Simple: Use it for simple assignments to improve code cleanliness.
  • Avoid Deep Nesting: If logic becomes complex, a standard if-else or switch is often easier to read and debug.
  • Type Matching: Both the true and false expressions must return the same type or be implicitly convertible to the same type.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.