byte overflow with unchecked

In this chapter you will learn:

  1. How to check byte overflow with unchecked
  2. Catching an underflow exception

byte overflow with unchecked

using System;/*  j a v  a  2 s . c o m*/

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

The code above generates the following result.

Catching an underflow exception

using System;/* ja  va  2s .co  m*/

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);}

  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to specify int literal
  2. Methods for int type
Home » C# Tutorial » Byte, Integer, Long
Integer Family
Integer ranges
byte
Convert to byte
Parse string to byte
byte format
byte octal and hexadecimal
byte binary operation
byte overflow with unchecked
int
int value
Compare int value
int calculation
int value overflow
int binary operation
Parse string to int value
Format int value
int in binary, octal and hexadecimal
long
long value calculation
ulong