← Back to C# Course | Chapter 4: Control Flow | Lesson 2 of 7

switch Statement कैसे लिखें

एक switch किसी menu जैसा है जहां आप item number बताते हैं और बिल्कुल वही dish पाते हैं। C# एक value को cases की एक list से compare करता है और जो मेल खाए उसे चलाता है।

In this page:

  1. switch Statement
Syntax
csharp
switch (value)
{
    case value1:
        // ...
        break;
    case value2:
        // ...
        break;
    default:
        // no case matched
        break;
}

switch Statement

एक switch statement एक value को कई case labels से compare करता है और matching block चलाता है। अगले पर fall through होने से रोकने के लिए हर case को एक break (या return) चाहिए। default किसी case से मेल न खाने वाली value को handle करता है।

Warning: C के विपरीत, C# non-empty cases के बीच implicit fallthrough की अनुमति नहीं देता — हर case को break, return, या goto से खत्म होना चाहिए।

उदाहरण: switch Statement

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        int day = 3;
        string name;

        switch (day)
        {
            case 1:
                name = "Monday";
                break;
            case 2:
                name = "Tuesday";
                break;
            case 3:
                name = "Wednesday";
                break;
            default:
                name = "Unknown";
                break;
        }

        Console.WriteLine(name);
    }
}
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. किसी case के आखिर में break भूल जाना, जो C# में एक compile error है क्योंकि fall through करने की अनुमति नहीं है।
  2. अप्रत्याशित values के लिए एक default case न जोड़ना।
  3. किसी case label में एक non-constant value का उपयोग करना, जबकि labels को constants होना चाहिए।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.