Nuriddin
Posted on May 30, 2022
C# 7.0 dan boshlab, switchga parametr qilib berilgan qiymatni belgilangan konstantaga teng yoki yo'qligini tekshirish uchun constant patterndan foydalanishimiz mumkinakan:
public static decimal GetGroupTicketPrice(int visitorCount) => visitorCount switch
{
1 => 12.0m,
2 => 20.0m,
3 => 27.0m,
4 => 32.0m,
0 => 0.0m,
_ => throw new ArgumentException($"Not supported number of visitors: {visitorCount}", nameof(visitorCount)),
};
Constant patternda switchga parametr qib berilgan qiymatni mamnaqa tipla bilan solishtirish mumkinakan anaqqisa π:
- Integer yoki floating-point sonlar
- Char yoki a string literal
- Boolean qiymat true yoki false
- Enum value
- e'lon qilingan const maydoni yoki mahalliy nomi
- null
tepadigi misoldaka qilib ko'rsataman:
public static decimal GetGroupTicketPrice(object visitorCount) => visitorCount switch
{
1 => 15.0m, // int qiymat bilan solishtirvotti
"string" => 12.0m, // string qiymat bilan solishtirvotti
'a' => 20.0m, // char qiymat bilan solishtirvotti
true => 27.0m, // bool qiymat bilan
"enum" => 32.0m, // enum qiymat
null => null, // null bilan
0 => 0.0m, // buyam int qiymat bn soliwtirvotti
_ => throw new ArgumentException($"Not supported number of visitors: {visitorCount}", nameof(visitorCount)),
};
Constant patterndan nullni tekshirishda ham foydalaniladi:
if (input is null)
{
return;
}
C# 9.0 dan boshlab, quyidagi misolda ko'rsatilgandaka, null bo'lmaganni tekshirish uchun negated null qilib tekwiriladi:
if (input is not null)
{
// ...
}
Uncha chunmagan bo'sela mamyaqqa o'tib ko'rvosela bo'ladi constant pattern!
π πͺ π
π©
Nuriddin
Posted on May 30, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.