Implicitly typed keyword - var in C#

What is var

var is a keyword in C#. It is used to declare the implicitly typed local variables. You can assign value of any type to var, and the compiler will decide the data type of value at the compile time. 

Example

var age=20;

var name="ABCD";

var number=23.3

To get the data type of value that has been assigned to the var, you can use GetType() method.

Console.WriteLine(age.GetType());     //output - System.Int32

Console.WriteLine(name.GetType());     //output - System.String

Console.WriteLine(number.GetType());    //output - System.Double

Initialization

The var must be initialized at the time of declaration. Otherwise the compiler gives the compile time error.

var age;      

error - implicit typed variables must be initialized

Multiple Declarations

Multiple var variables cannot be declared on the same line.

var age=23,Id=32;

error- Implicitly typed variables cannot have multiple declarators

var as a function parameter

var cannot be used as function parameter

function Display(var age)
{
}

var in for, foreach loop

var can be used in for and foreach loop for declaring local variable.

for(var i=0;i<10;i++)
{
//code to execute
}



foreach(var i in result)
{
//code to execute
}

Comments

Popular posts from this blog

Classes and objects in C#

Data types in C#