"Relational pattern"lar haqida...

nuriddin321

Nuriddin

Posted on May 30, 2022

"Relational pattern"lar haqida...

C# 9.0 dan boshlab, switchga parametr qilib berilgan qiymatni aniq qiymatlar bilanmasde malum bir diapazondigi qiymatla bilan solishtiraish uchun relational patterndan foydalanamiz:

Console.WriteLine(Classify(13));  // output: Too high
Console.WriteLine(Classify(double.NaN));  // output: Unknown
Console.WriteLine(Classify(2.4));  // output: Acceptable

static string Classify(double measurement) => measurement switch
{
    < -4.0 => "Too low",
    > 10.0 => "Too high",
    double.NaN => "Unknown",
    _ => "Acceptable",
};
Enter fullscreen mode Exit fullscreen mode

Relational patterda siz <, >, <= yoki >= kabi solishtirish operatorlaridan foydalanishingiz mumkin. Relational patternning o'ng tomoni constant ifoda bo'lishi kerak.
Constant qiymat int, float, char yoki enum tipidagi bo'lishi mumkin.

Ifodaning natijasi ma'lum diapazonda ekanligini tekshirish uchun uni "conjunctive and pattern" bilan moslang :

Console.WriteLine(GetCalendarSeason(new DateTime(2021, 3, 14)));  // output: spring
Console.WriteLine(GetCalendarSeason(new DateTime(2021, 7, 19)));  // output: summer
Console.WriteLine(GetCalendarSeason(new DateTime(2021, 2, 17)));  // output: winter

static string GetCalendarSeason(DateTime date) => date.Month switch
{
    >= 3 and < 6 => "spring",
    >= 6 and < 9 => "summer",
    >= 9 and < 12 => "autumn",
    12 or (>= 1 and < 3) => "winter",
    _ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
};
Enter fullscreen mode Exit fullscreen mode

Agar ifoda natijasi null bo'lsa yoki constant qiymatni nullable qiymatga convert qilish imkoni bo'lmasa relational pattern ifodaga mos kelmaydi.
Qo'shimcha ma'lumot olish uchun relational pattern bo'limiga qarang.

πŸ’– πŸ’ͺ πŸ™… 🚩
nuriddin321
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.

Related