20 April 2014

var keyword in C# exaplined: when to use it and when not

We tend to use the var keyword often to declare the class variables while writing C# code. This may be to avoid importing the namespaces or to save time writing the full name of the class variables. But it's very important to understand why the var keyword introduced?

var keyword meant to use only when the type of the variable is not known to you (i.e. Developer) and only known to the compiler. Use the var keyword when you are working with anonymous types. Let's consider an example.

var customers= from cust in customers
               where cust.City== "Bangalore" 
               select new { cust.Name, cust.Phone }; 
               //anonymous type

And var shouldn’t be used when you know the variable type already. Declare the variable with explicit type name like in the below example.

public class Customer
{
 string Name{get;set;}
 string City{get;set;}
 string Phone{get;set;}
}

var customers= from customer in customers 
                where customer.Name ="Ranganatha"
                select customer;

In the above C# LINQ query example we already know that, we are selecting Customer type, which is not an anonymous type. So usage of var keyword to declare the list of customer is not encouraged while writing code. So in the above example using explicit type declaration makes more sense.

// Use explicit type declaration when 
// type is already known
List<Customer> customers= from customer in customers 
                where customer.Name ="Ranganatha"
                select customer;

When code is more explicit in nature, it becomes more readable. Remember code is written once, however debugged and read more times. So readability of the code important.

No comments:

Post a Comment