Csharp/CSharp Tutorial/Data Type/unchecked

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

An Unchecked Block Example

<source lang="csharp">using System; public class Program {

 public static void Main()
 {
         unchecked
         {
            // int.MaxValue equals 2147483647
            int n = int.MaxValue;
             n = n + 1 ;
            System.Console.WriteLine(n);
         }
 }

}</source>

Mark expressions as unchecked

<source lang="csharp">using System; class MainClass {

   public static void Main()
   {
       unchecked
       {
           byte a = 55;
           byte b = 210;
           byte c = (byte) (a + b);
       }
   }

}</source>

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.
   at MainClass.Main()

Overflow the max value of a System.Byte

<source lang="csharp">using System; using System.Collections.Generic; using System.Text;

 class Program
 {
   static void Main(string[] args)
   {
     byte b1 = 100;
     byte b2 = 250;
     try
     {
       byte sum = unchecked((byte)(b1 + b2));
       Console.WriteLine("sum = {0}", sum);
     }
     catch (OverflowException ex)
     {
       Console.WriteLine(ex.Message);
     }
   }
 }</source>

unchecked marker

<source lang="csharp">using System; using System.Collections.Generic; using System.Text;

 class Program
 {
   static void Main(string[] args)
   {
     // Declare two shorts to add.
     short numb1 = 30000, numb2 = 30000;
     // This will not throw an exception.
     unchecked
     {
       short answer = (short)Add(numb1, numb2);
       Console.WriteLine("{0} + {1} = {2}",
           numb1, numb2, answer);
     }
   }
   static int Add(int x, int y){ return x + y; }
 }</source>