In .Net, when you simply declare a variable with datatype int, it is explicit declaration
- int i = 0; //explicit
- var v = 0; //implicit
Why use var?
The most important aspect of var in existence is LINQ with Anonymous Type. Using var makes your code very simple and short.
Let's first take an example code of LINQ with Anonymous Type without using var.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace ConsoleApplication1
- {
- class Details
- {
- public int Length;
- public string Value;
- }
- class LINQ
- {
- static void Main(string[] args)
- {
- string[] Names = {
- "Sandeep", "Abhay", "Ritesh"
- };
- IEnumerable < Details > details = from x in Names select new Details
- {
- Length = x.Length, Value = x
- };
- foreach(Details d in details)
- {
- Console.Write(string.Format("Name : {0}, Length : {1}\n", d.Value, d.Length));
- }
- System.Threading.Thread.Sleep(2000);
- }
- }
- }
Example of LINQ with Anonymous Type using var.
- using System.Collections.Generic;
- using System.Linq;
- namespace ConsoleApplication1
- {
- class LINQ
- {
- static void Main(string[] args)
- {
- string[] Names = {
- "Sandeep", "Abhay", "Ritesh"
- };
- var v = from x in Names select new
- {
- Length = x.Length, Value = x
- };
- foreach(var d in v)
- {
- Console.Write(string.Format("Name : {0}, Length : {1}\n", d.Value, d.Length));
- }
- System.Threading.Thread.Sleep(2000);
- }
- }
- }

Gowtham RajamanickamPosted Apr 8, 2016, 9:59 AM
good one..