C# standard control-flow constructs प्रदान करता है — conditionals (if, ), loops (, , ), और branching (, , ) — साथ ही switch expressions और pattern matching जैसे modern enhancements जो code को अधिक concise बनाते हैं।
switchforforeachwhilebreakcontinuereturnif (score >= 90)
grade = "A";
else if (score >= 80)
grade = "B";
else
grade = "F";
// ternary and null-coalescing
string status = age >= 18 ? "adult" : "minor";
string name = input ?? "default"; // ?? — use default if input is null
name ??= "fallback"; // ??= assign if null
// traditional switch
switch (day)
{
case "Sat":
case "Sun":
type = "weekend";
break; // break required (no fall-through)
default:
type = "weekday";
break;
}
// switch EXPRESSION (C# 8) — concise, returns a value, with pattern matching
string type = day switch
{
"Sat" or "Sun" => "weekend",
_ => "weekday", // _ = default
};
// pattern matching in switch
string describe = obj switch
{
int n when n > 0 => "positive int",
string s => $"string of length {s.Length}",
null => "null",
_ => "other",
};
Modern switch expression concise है (एक value लौटाती है, कोई break नहीं), और शक्तिशाली pattern matching का समर्थन करती है (types, conditions, और बहुत कुछ match करना) — verbose traditional switch पर एक बड़ा सुधार।
for (int i = 0; i < 10; i++) { }
foreach (var item in collection) { } // iterate any IEnumerable
while (condition) { }
do { } while (condition); // runs at least once
foreach (किसी भी IEnumerable को iterate करना) collections के लिए idiomatic loop है।
foreach (var item in items)
{
if (item.Skip) continue; // next iteration
if (item.Stop) break; // exit loop
}
return result; // exit method
Control flow हर program में logic को व्यक्त करने का बुनियादी तंत्र है, इसलिए C# के constructs को समझना मूलभूत रोजमर्रा का ज्ञान है।
हालांकि बुनियादी चीज़ें standard हैं, modern C# enhancements को जानना और उपयोग करना सार्थक है: switch expression (C# 8+) traditional switch पर एक महत्वपूर्ण सुधार है — concise, value-returning, कोई fall-through bugs नहीं (कोई भूला हुआ break नहीं), और pattern matching का समर्थन करती है (types, conditions, values, और structure पर match करना), जो जटिल conditional logic को nested if-else chains की तुलना में कहीं अधिक स्वच्छ बनाती है।
null-coalescing operators (??, ??=) स्वच्छ null handling प्रदान करते हैं, और foreach collections को iterate करने का idiomatic तरीका है।
इन constructs को जानना और modern, अधिक expressive रूपों को प्राथमिकता देना (verbose switch statements के बजाय pattern matching के साथ switch expressions, defaults के लिए null-coalescing) स्वच्छ, idiomatic C# लिखने के लिए रोजमर्रा का ज्ञान है।
switch expression और pattern matching विशेष रूप से अधिक functional, concise code की ओर modern C# के विकास को दर्शाते हैं, जिससे वे बेहतर code लिखने और इन features का व्यापक उपयोग करने वाले current C# codebases को पढ़ने दोनों के लिए समझना महत्वपूर्ण हो जाते हैं।