← Back to C# Course | Chapter 3: Operators | Lesson 5 of 6

Ternary Operator क्या है

Ternary operator एक छोटी एक-line choice है: 'क्या बारिश हो रही है? umbrella लो, नहीं तो sunglasses लो'। यह बिना पूरे if-else के दो values में से चुनता है।

In this page:

  1. The Ternary Operator
Syntax
csharp
type result = condition ? valueIfTrue : valueIfFalse;

The Ternary Operator

Ternary operator condition ? valueIfTrue : valueIfFalse एक साधारण if/else का एक compact one-line विकल्प है। यह हमेशा अपने दो branches में से बिल्कुल एक evaluate होता है। Ternary expressions को nest किया जा सकता है लेकिन ऐसा करना जल्दी readability को नुकसान पहुंचाता है।

Note: छोटे, simple value selection के लिए ternary का उपयोग करें — logic जटिल होने पर if/else पर वापस जाएं।

उदाहरण: The Ternary Operator

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        int age = 16;
        string status = age >= 18 ? "adult" : "minor";

        Console.WriteLine(status);
        Console.WriteLine(age % 2 == 0 ? "even" : "odd");
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. कई ?: operators को nest करना जिससे code पढ़ना मुश्किल हो जाता है।
  2. अलग types की branches का उपयोग करना जिनमें कोई common type न हो, जो एक compile error है।
  3. Ternary operator को किसी expression के बजाय एक statement की तरह उपयोग करना, जैसे x > 0 ? Print() : Skip();।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.