C Sharp (C#) Integer Data Type


Integer datatype is most widely used datatype to store numbers in C#. Variables of type int are mostly used to control loops, to index arrays and for other math functions. Depending on the requirements remaining datatypes that hold numbers are chosen (example: short or long). This is a signed datatype, so it can hold both negative and positive numbers with a range from –2,147,483,648 to 2,147,483,647.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1 = 200000000;
            int num2 = 200000000;
            int num3 = num1 + num2;
            Console.WriteLine("The addition of num1 and num2 is : {0}", num3);
            Console.ReadLine();

            //Here the numbers are more than the limit that int variable could hold.
            int num4 = 2000000001;
            int num5 = 2000000003;
            int num6 = num4 + num5;
            Console.WriteLine("The addition of num4 and num5 is : {0}", num6);
            Console.ReadLine();           
        }
    }
}

Output :

The numbers in the code, num1 and num2 values are within the range of int datatype. So they did not throw any garbage value. But the num4 and num5 are outside the range of int datatype, hence when added, it gave a garbage value as output. We could avoid it by using a datatype which could hold higher numbers. (like a long datatype)

C Sharp Datatypes Home Page

No comments: