C# Numeric Types

C# Numeric Types: A total of 9 Integer Type Value Types have been defined in C# according to the following table. Out of which, the char value type is basically defined to represent the characters, and we will learn about it further. At the same time, the other 8 Integer Data Types are used for Numeric Calculation only.

Type Width Range Suffix
byte 8-Bit 0 to 255
sbyte 8-Bit –128 to 127
short 16-Bit –32,768 to 32,767
ushort 16-Bit 0 to 65,535
int 32-Bit –2,147,483,648 to 2,147,483,647
uint 32-Bit 0 to 4,294,967,295 U / u
long 64-Bit –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 L / l
ulong 64-Bit 0 to 18,446,744,073,709,551,615 UL / ul

As we can understand from the above table that when we have to store the signed number in a variable, then we declare the variable/constant using byte, short, int, or long keywords according to the range of the number.

Whereas if the Integer value we want to store in a variable can never be negative, then to store such values, we need to use byte, short, int, or long keywords depending on the range of the value. By doing that, Variable / Constant has to be declared.

For example, we all know that the maximum age limit of humans is generally up to 100–150 years. Therefore, we can use byte data type to store age in a computer because the maximum number that can be stored in a variable of byte type is 255.

Also, the age of any person can never be negative] That’s why byte data type is the most suitable data type to store age because we cannot store negative value in the Variable of byte data type. If we try to do so, generating a compiler error prevents us from doing so.

In this way, to store the age of a student in the computer, we can create an identifier as follows:

byte age;

If we want to store the Salary of an Employee in Computer, then we can create the short type of Variable as follows to store Salary-

short salary;

If the salary of Employees in a company is up to 32767, then we can use a short data type. But if the salary of Employees in a company is more than this, then we can declare a variable of type int as follows to store the salary-

int salary;

Sometimes we need to calculate very large numbers. For example, if we want to store the total population of a country on a computer, then we need to store a very large number. This requirement cannot be fulfilled by data types of type byte, short, or int.

So in this situation, we have to declare a variable of type long. This data type is used when very large values ​​have to be stored in the computer. We can declare the Variable of this Data Type as follows-

long population;

In the above table, we have also specified Suffix with uint, long, long data types. So when we declare any of these three types of Variable/Constant, it is necessary to specify the associated Suffix with the value while assigning the values ​​to them.

For example, if we want to assign a value to the above Variable, then our assignment statement should be something like this:

population = 1212121212121212F;

As we can see in the above statement that we have specified “L” Suffix with Value. This Suffix is ​​specified so that the compiler knows that we are assigning a value to a variable of a long type.

The .NET Platform treats int and long types as native data types. Therefore, if memory efficiency is not very important, then all necessary variables related to Integer should be declared of int or long type only.

Integer Division Error

When we process with Integer Values, then Integer Value is always Truncate while performing Division Operation. That is, if a decimal number is generated after the division, then the generated decimal is ignored by the Part Compiler. like:

// File Name: DivisionError.cs
using System;
namespace CSharpFundamentals
{
    class DivisionError
    {
        private static void Main(string[] args)
        {
            int value1 = 2/3;
            int value2 = 5;
            int result = value2 / value1;
            Console.Write("Result: {0}", result);
        }
    }
}

// Output:
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
   at CSharpFundamentals.DivisionError.Main(String[] args)

In the above code, when two are divided by 3, the value 0.666. is generated as a result, which is a decimal number. Whereas the value generated from this expression is being stored in the variable value1 of an Integer type by the following statement:

        

int value1 = 2/3;

As a result, the C# Runtime just stores 0 in value1, ignoring the number after the decimal when this statement is executed. 

That’s why in the above code when the following statement is executed:

       

int result = value2 / value1;

So the value five stored in the value2 Variable is actually being divided by the value 0 stored in value1, which is not possible. That is why the above program is not compiled properly; rather, we get an error in the output.

Integer Overflow Error

Similarly, when we perform an arithmetic operation with an Integer Data Type, the Data of Integer Type can also overflow. But when the Integer Overflow condition occurs, .NET Runtime does not display any kind of error to us, but in the case of Overflow, Extra Bits are ignored by the compiler, and after doing so,,, the binary that is left is removed from that binary. The generated value itself is stored in the Variable. Like:

// File Name: IntegerOverflow.cs
using System;

namespace CSharpFundamentals
{
    class IntegerOverflow
    {
        private static void Main(string[] args)
        {
            int value1 = int.MinValue;
            Console.WriteLine("Minimum Range of Integer: {0}", value1);

            int total = value1 - 1;
            Console.WriteLine("Maximum Range of Integer: {0}", total);
        }
    }
}

// Output:
    Minimum Range of Integer: -2147483648
    Maximum Range of Integer: 2147483647

As we can see in the above example that we have assigned the value of Minimum Range of Integer to the value1 Variable, which we can see in the first line of the output. But when we reduce one from this Minimum Range, we get the Maximum Range of Integer.

This is because int is a 32-bit data type in the .NET Framework, with a total of 31 bits giving the maximum range of positive numbers, while the left-most Bit represents the number’s sign.

If the value of Left-Most Bit is 0, then the number is positive, while if it is 1, the number is negative. In this way, the minimum negative number that can be stored by an Integer is stored in the memory as follows:

10000000 00000000 00000000 0000000

As a result, when the compiler executes the following statement of the above program:

int value1 = int.MinValue;

Then the number -2147483648 is stored as the above binary in the value1 Variable. But as soon as we subtract 1 in this number through the following statement:

int total = value1 – 1;

The above binary stored in value1 gets changed as follows:

01111111 11111111 11111111 11111111

Which represents a value equal to the positive number 2147483647.

That is, when we add something to the Maximum Integer Value that can be stored in an Integer Value, a situation of Overflow is created. Whereas we subtract some of the Minimum Integer Value that can be stored in an Integer Value, then a situation of Underflow is created, and in both cases, we neither get any error nor get the correct result.

So to handle this type of situation, .NET Framework provides us a special operator named checked. The specialty of this operator is that whenever we are doing ++, –, +, +, -, *, / or manual typecasting process with Integer Types and the resultant value to be generated is going out of its limit. If it happens, then this operator generates an OverflowException, which lets us know that our Integer Related Expression is not generating the correct result, and we need a bigger Integer Data Type to handle the Current Expression normally.

// File Name: checkedOperator4IntegerOverflow.cs
using System;

namespace CSharpFundamentals
{
    class checkedOperator4IntegerOverflow
    {
        private static void Main(string[] args)
        {
            int value1 = int.MinValue;
            Console.WriteLine("Minimum Range of Integer: {0}", value1);

            int total = checked(value1 - 1);
            Console.WriteLine("Maximum Range of Integer: {0}", total);
        }
    }
}

// Output:
Minimum Range of Integer: -2147483648

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.  at CSharpFundamentals.checkedOperator4IntegerOverflow.Main(String[] args)

We can modify our program by using the checked operator in our above program itself in the following way so that that program also generates an exception in the case of Integer Overflow:

As we can see in the above program, for the Integer Expression, we need to check for the condition of Overflow; we specify that expression between the checked() method. As a result, this time, when this program is run, we see an Exception error according to the output of this program.

When we have to check more than one Integer Expression for Overflow, then all Integer Expressions have to be Curly Enclose between Braces. Like: 

{
            int value1 = int.MinValue;
            int total = checked(value1 - 1);
        }

We cannot use the checked operator with a float or double type because both of these return special “infinite” values in the case of Overflow, which we will discuss further.

Leave a Comment