Var Data Type in C#
C# 3.0 adds the interesting behavior of Declaring Local Variables Implicitly. This means that there is no need to mention the data type when declaring a variable. A local variable can be declared implicitly using the var keyword in C#.
Declaring local variables implicitly has some restrictions; the variable must be initialized to some expression that can not be null.
var a= 10;
var z = "Rekha";
The primary reason for its existence is the introduction of anonymous types in C#.
Another point to stress is that variable inference does not work for class-level fields or method arguments or anywhere else other than for local variables in a method.
Advantages of Var Data Type
- Less typing with no loss of functionality
- Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types
- Makes it so you don't have to write the same name twice in a variable declaration.
- Some features, such as declaring a strongly typed anonymous type local variable, require the use of var
Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Namesp1
{
class Program
{
static void Main(string[] args)
{
var x = Convert.ToInt32(Console.ReadLine());
var y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The Sum Is : " + (x + y));
}
}
}
Example 2
using System;
namespace ConsoleApplication1
{
class A
{
public static void Main()
{
int sum = 0;
int[] arr = new int[10];
for (int i = 0; i < 10; i++)
{
arr[i] = i;
}
foreach (var x in arr)
{
Console.WriteLine("Value is: " + x);
sum =sum + x;
}
Console.WriteLine("Sum of array elements is : " + sum);
}
}
}
Output


Abhishek KumarPosted Feb 28, 2019, 7:21 AM
Good article..
Upendra Pratap ShahiPosted Sep 30, 2015, 3:05 AM
nice..
Anil pandeyPosted Jun 27, 2012, 1:18 AM
Good example..
Avinash SingheditedPosted Feb 6, 2010, 5:25 AMEdited Feb 6, 2010, 5:26 AM
hi rekha, i viewed this article. but i confused what is the type of var in C#.net. because i don't have more knowledge about web currently i moved.
venkat reddyPosted Aug 17, 2009, 2:41 AM
Just adding onemore point, when you are using Linq concepts this is much more useful below it the example var EmpDetails = from comp in ListCompany select new<o:p> { Emp = (from emp in comp.ListEmp<o:p> select new { Company = comp.Name, emp }) }; </o:p></o:p> -Venky
Former memberPosted Aug 13, 2009, 3:06 AM
keep it up :)