Csharp/CSharp Tutorial/Data Type/byte overflow
byte overflow with unchecked
<source lang="csharp">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); } }
}</source>
Working with unchecked code b4 = 44
Catching an underflow
<source lang="csharp">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);} }
}</source>
System.Byte stats: Max value of byte is 255. Min value of byte is 0. Catching an underflow