int value overflow

In this chapter you will learn:

  1. Integral type overflow
  2. Catch OverflowException Exception

Integral type overflow

The integral type may overflow. The following example shows that the overflow happens when subtracting one from minimum int value.

using System;//from   j  a  v  a2 s  .c  o  m

class Program
{
    static void Main(string[] args)
    {
        int i = int.MinValue;
        
        int result = i-1;
        Console.WriteLine("i=" + i);

        Console.WriteLine("result="+result);
        Console.WriteLine("result is int.MaxValue:" + (result == int.MaxValue));


    }
}

The output:

Catch OverflowException Exception

using System;//from  jav  a2 s. c  om
   
class MainClass
{
    public static void Main()
    {
        try
        {
            checked
            {
                int Integer1;
                int Integer2;
                int Sum;
   
                Integer1 = 9999999999;
                Integer2 = 2000000000;
                Sum = Integer1 + Integer2;
            }
        }
        catch(OverflowException)
        {
            Console.WriteLine("A mathematical operation caused an overflow.");
        }
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Bitwise AND of Integer
  2. Shifting an integer value
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