When to use var instead of type in C#.


Example 1

var i=10;
int i=10;


Here it is an optional to declare i as var type. Because we know the value is integer type.

Example 2

string[] fruits = { "mango", "apple", "grape", "banana" };
foreach (var s in fruits)
{
Console.WriteLine(s);
}
//OR
foreach (string s in fruits)
{
Console.WriteLine(s);
}


it is also an optional to use var instead of string. Because we know all elements are string.

Example 3
Use var when we have to deal with anonymous type data.

var anonArray = new[] { new { FirstName = "Dev", Age = 24 }, new { FirstName = "Vikas", Age = 21 } };

foreach (var arr in anonArray)
{
    Console.Write(arr.FirstName);
    Console.WriteLine(arr.Age);
}
Console.ReadKey();