Thursday, August 25, 2011

When to use var keyword in C#

Microsoft introduced “var” keyword in C# 3.0. The purpose of using this keyword is when you don’t know type of variable. The technical term for var is "implicitly typed local variable declaration". The variable itself is still statically typed (the type is determined when the code is compiled), and it is still strongly typed (the type cannot change once it has been declared). the compiler infers the type of the variable based upon the initialize for the variable. It is mainly use in anonymous methods, LINQ etc. Some of the programmers use this variable frequently in declaration. Below is some examples how to use var:

 
//this will compile as Hotel class
 var list = from hotel in this.Hotels
     where (hotel.City.Contains(searchCriteria))
     orderby hotel.Id
     select hotel;

 // i is compiled as an int
 var i = 5;

 // s is compiled as a string
 var s = "Hello";

 // a is compiled as int[]
 var a = new[] { 0, 1, 2 };

 // expr is compiled as IEnumerable
 // or perhaps IQueryable
 var expr =
    from c in customers
    where c.City == "London"
    select c;

 // employee is compiled as an anonymous type
 var employee = new { Name = "Neeraj", Age = 31 };


Benefits of using Var

    It removes code noise eg. redundant code in declaration of generics.
    It doesn’t require using directive.
    Most obvious use in LINQ and Anonymous type.


Read more: Beyond relational
QR: when-to-use-var-keyword-in-c.aspx

Posted via email from Jasper-Net