DEV Community

Cover image for Checked & Unchecked statements in C# reference
Ozodbek
Ozodbek

Posted on

Checked & Unchecked statements in C# reference

Bugun sizlar bilan, Quyidagi savollar bilan bog'liq miflarni sindiramiz 🛠️

  • Overflow checking Context ?
  • Default overflowni tekshirish Contexti ?
  • C# tili spefikatsiyasidan bir shingil ?
  • Vahokazo ?

Checked va Unchecked iboralari arifmetik va Convertationlar uchun Overflow bo'lishni tekshirish contextini belgilaydi. Butun son arifmetik tomondan to'lib ketganda Overflow checkings bizga nima sodir bo'lganligini ko'rsatadi. Masalan: E'tibor berganmisiz, Int tipiga Int.MaxValue dan ko'p miqdorda qiymat berilganda System.OverFlowException compilator tomonidan sizga tashlanadi. Agar doimiy ifodada Overflow sodir bo'lsa, compilation vaqtida xatolik yuz beradi. Aytgancha bu turdagi Exceptionlar System kutubxonasiga tegishli,
Xullas quyidagi bir shingil codeda qisqa va lo'nda qilib ko'rishimiz mumkin.

uint a = uint.MaxValue;

unchecked
{
    Console.WriteLine(a + 3);  // output: 2
}

try
{
    checked
    {
        Console.WriteLine(a + 3);
    }
}
catch (OverflowException e)
{
    Console.WriteLine(e.Message);  // output: Arifmetik operatsiya to'lib ketishga olib keldi 
}
Enter fullscreen mode Exit fullscreen mode

Double tipida ham shunday qilib ko'rsa bo'ladi .

double a = double.MaxValue;

int b = unchecked((int)a);
Console.WriteLine(b);  // output: -2147483648

try
{
    b = checked((int)a);
}
catch (OverflowException e)
{
    Console.WriteLine(e.Message);  // output: Arithmetic operation resulted in an overflow.
}
Enter fullscreen mode Exit fullscreen mode

Checked va Unchacked haqida yana bir kattaroq misol. Bu misolni review qilishingizni maslahat beraman.

int Multiply(int a, int b) => a * b;

int factor = 2;

try
{
    checked
    {
        Console.WriteLine(Multiply(factor, int.MaxValue));  // output: -2
    }
}
catch (OverflowException e)
{
    Console.WriteLine(e.Message);
}

try
{
    checked
    {
        Console.WriteLine(Multiply(factor, factor * int.MaxValue));
    }
}
catch (OverflowException e)
{
    Console.WriteLine(e.Message);  // output: Arithmetic operation resulted in an overflow.
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)