C# standard control-flow constructs પ્રદાન કરે છે — conditionals (if, ), loops (, , ), અને branching (, , ) — વતમાન savvy enhancements જેમ કે switch expressions અને pattern matching સાથે જે કોડને વધુ 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",
};
આધુનિક switch expression concise છે (value return કરે છે, કોઈ break નહીં), અને શક્તિશાળી pattern matching ને support કરે છે (types, conditions, અને વધુને match કરીને) — વર્બોસ 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નું iteration કરીને) 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 વ્યક્ત કરવાની મૂળભૂત mechanism છે, તેથી C#'s constructs સમજવું એ fundamental everyday knowledge છે.
જ્યારે basics standard છે, આધુનિક C# enhancements જાણવા અને ઉપયોગ કરવા યોગ્ય છે: switch expression (C# 8+) traditional switch પર નોંધપાત્ર સુધાર છે — concise, value-returning, કોઈ fall-through bugs નહીં (કોઈ ભૂલેલો break નહીં), અને pattern matching ને support કરે છે (types, conditions, values, અને structure પર match કરીને), જે complex conditional logic ને nested if-else chains કરતા ખૂબ સ્વચ્છ બનાવે છે.
null-coalescing operators (??, ??=) clean null handling પ્રદાન કરે છે, અને foreach એ collections iterate કરવાનો idiomatic રસ્તો છે.
આ constructs જાણવા અને આધુનિક, વધુ expressive forms (verbose switch statements કરતા switch expressions with pattern matching, defaults માટે null-coalescing) ને પ્રાધાન્ય આપવું એ clean, idiomatic C# લખવા માટે everyday knowledge છે.
Switch expression અને pattern matching ખાસ કરીને આધુનિક C#'s evolution ને functional, concise code તરફ પ્રતિબિંબિત કરે છે, જે તેમને સમજવા માટે બે બાબતોમાં મહત્વપૂર્ણ બનાવે છે — વધુ સારો કોડ લખવા માટે અને વર્તમાન C# codebases વાંચવા માટે જે આ features ને વ્યાપક રીતે ઉપયોગ કરે છે.