Csharp/CSharp Tutorial/Data Type/byte overflow

Материал из .Net Framework эксперт
Версия от 12:18, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

byte overflow with unchecked

using System;
class MainClass
{
  static void Main(string[] args)
  {
    Console.WriteLine("Working with unchecked code");
    try
    {
      unchecked
      {
        byte b5 = 100, b6 = 200;
        byte b4 = (byte)(b5 + b6);
        Console.WriteLine("b4 = {0}", b4);       
      }
    }
    catch(OverflowException e)
    { 
      Console.WriteLine(e.Message);
    }    
  }
}
Working with unchecked code
b4 = 44

Catching an underflow

using System;
class MainClass
{
  static void Main(string[] args)
  {
    Console.WriteLine("System.Byte stats:");
    Console.WriteLine("Max value of byte is {0}.", byte.MaxValue);
    Console.WriteLine("Min value of byte is {0}.", byte.MinValue);
    Console.WriteLine("Catching an underflow");
    try
    {
      byte a = 9, b = 9;
      byte c = (byte)(a + b + -100);
    }
    catch(OverflowException e){Console.WriteLine(e);}
  }
}
System.Byte stats:
Max value of byte is 255.
Min value of byte is 0.
Catching an underflow