In C#, we can create local variable without specifying its type. The C# var
keyword is used to create implicit typed local variables. The C# compiler infers the types of variable on the basis of assigned value.
The var
keyword can be used in following context:
The var
keyword has following restrictions:
If the compiler can infer the type from the initialization expression, we can use the keyword var
to declare variable type.
For example:
var x = "hello";
var y = new System.Text.StringBuilder();
var z = (float)Math.PI;
This is equivalent to:
string x = "hello";
System.Text.StringBuilder y = new System.Text.StringBuilder();
float z = (float)Math.PI;
Implicitly typed variables are statically typed.
For example: the following generates a compile-time error:
var x = 15;
x = "hello"; // Compile-time error; x is of type int
Let's see some examples:
Here, we have created integer, string and array type local variables:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// integer
var a = 200;
// string
var s = "hello word from XDevSpace!";
// array
var arr = new[] { 1, 2, 3 };
Console.WriteLine(a);
Console.WriteLine(s);
Console.WriteLine(arr[2]);
Console.ReadLine();
}
}
}
Output:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// Declaring and initializing
// implicitly typed variables
var v1 = 90;
var v2 = "Welcome! Devs";
var v3 = 140.87d;
var v4 = false;
// Display the type of the variables
Console.WriteLine("Type of 'v1' is : {0} ", v1.GetType());
Console.WriteLine("Type of 'v2' is : {0} ", v2.GetType());
Console.WriteLine("Type of 'v3' is : {0} ", v3.GetType());
Console.WriteLine("Type of 'v4' is : {0} ", v4.GetType());
Console.ReadLine();
}
}
}
Output:
Note: Implicitly typed local variables can be used as a local variable in a function, in foreach, and for loop, as an anonymous type, in LINQ query expression, in using statement etc.