C# 3.0 introduced a new implicit type var for variables that are declared at method scope. The datatype of these variables is determined by the compiler when a value is assigned to it.

Things to remember

  • var should be declared and initialized in a single statement.
  • var can only be declared as a local variable.

Example

using System;   //Adding namespaces
namespace LearnCSharp //Namespace of the class
{
class Program //The class
{
static void Main(string[] args) //Main method
{
var a = 10;
var b = 10.5;
var c = "Hello World";
Console.WriteLine("Type of a is {0}", a.GetType());
Console.WriteLine("Type of b is {0}", b.GetType());
Console.WriteLine("Type of c is {0}", c.GetType());
Console.ReadKey();
}
}
}

Output

Type of a is System.Int32
Type of b is System.Double
Type of c is System.String

Following example shows how var can be used when no predefined data types for variables are known.

Example

using System;   //Adding namespaces
namespace LearnCSharp //Namespace of the class
{
class Program //The class
{
static void Main(string[] args) //Main method
{
System.Collections.ArrayList list = new System.Collections.ArrayList();
list.Add(1); //Integer
list.Add(10.5); //Double
list.Add("Hello World"); //String

foreach(var item in list)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}

Output

1
10.5
Hello World