Lesson 2.7

int data type C# - programming example


Objective

What is int data type in c#?
How to declare and initialize
Programming examples
Conversion and Casting

What is int Data Types in C#?

"Int is signed 32-bit integer type data type which is derived from System.Int32 Class. It stores value between -2,147,483,648 to 2,147,483,647. It is widely used data type in csharp."

TypeRangeSize.Net Framework type
int-2,147,483,648 to 2,147,483,647Signed 32-bit integerSystem.Int32

Declaration and Initialization

You can declare int data type as follow:

		  
  int num1=35;  
  

		  

Note:if the value of int variable exceed from its range a compilation error occurs:

Constant value 'xxx' cannot be converted to a 'int'

Programming Example

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

namespace int_data_type
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1, num2, result;
            num1 = 20;
            num2 = 30;
            result = num1 * num2;
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

		  

Output

600
_

Conversion

If you are doing arithmetic operation using int variable; it is not necessary to convert right hand side value into int data type. for example:

Correct Method
  result = num1 * num2; //Correct: Implicit Conversion
		  

Correct Method
  result = (int)(num1 * num2); //Correct: Explicit Conversion
		  

Implicit Conversion - No need to convert when left hand side data type is: 
  long, float, double or decimal
  
  Example:
  
  int a=5, b=6;
  long result=a+b;

Summary

int is signed 32-bit integer type data type which stores value between 0 to 65,535. It is mostly used for storing numeric value. In the next chapter we will discuss on uint data type.

BackNext