When To Use "Var" As A Type

It has been quite a long time since var was introduced, yet it remains a topic of debate among .NET developers. Everyone has a different understanding about when to use "var" as a type. A couple of days ago, I was also a part of one such discussion, and so through this article, I would like to share my understanding of the topic.

Readability
 
Every developer has all the rights to use var as and when they like, it's just a matter of one's choice. However, one must keep in mind that the every line of code should be self-explanatory and developer-readable. Let's have a look at the below code:
  1. public void SomeMethod()  
  2. {  
  3.     // first approach - implicit type casting  
  4.     var radius = 3;  
  5.     var text = "some string literal";  
  6.   
  7.     // second approach - explicit type casting  
  8.     int radius = 3;  
  9.     string text = "some string literal";  
  10. }  
Well, the above code, written with either of the approaches, will work just fine. But if you ask me to choose, I would always prefer the first one. Why? Because the code itself tells me that radius is an integer and text is a string. Now some would argue that even the second one does the same. I do agree, but as I mentioned it's just a matter of choice.
  
Let's have a look at some more examples, which we commonly see in our day-to-day life (speaking as a developer),
  1. CustomSaleInvoiceNumberService service = 
  2.           new CustomSaleInvoiceNumberService(paramOne, paramTwo, paramThree);   
  3. Dictionary<int, IEnumerable<Product>> stockProducts = 
  4.           new Dictionary<int, IEnumerable<Product>>();    
  5.     
  6. // we can rewrite the above two lines using 'var', making them more readable  
  7.   
  8. var service = new CustomSaleInvoiceNumberService(paramOne, paramTwo, paramThree);  
  9. var stockProducts new Dictionary<int, IEnumerable<Product>>();    
In the above code, the first two statements represent the typical way of creating an object. Using var, in the later ones did nothing magical expect that the two statements are more readable now and equally easy to understand.
 
When we use var here, the reader would still be able to derive the semantics of the code while looking at it. It is pretty easy to derive the type of the two variables just by looking at them. So, I think, using var in such scenarios, makes complete sense.

Maintainability
 
Assume a method CalculateTotalAmount, that uses an integer array amounts, and the value at index 2 is being used to initialize a variable transactionAmount. The variable is then passed as a parameter to another method CalculateVAT. Notice that the type of parameter that our method CalculateVAT expects is an integer. And while writing this code, the developer is certain about the type of transactionAmount being an integer. Therefore, he decides to use var as a type and not int.
  1. public decimal CalculateTotalAmount()    
  2. {    
  3.     // some code here    
  4.     .....    
  5.     var transactionAmount = amounts[2].TransactionAmount;    
  6.     totalAmount = CalculateVAT(transactionAmount);    
  7.     
  8.     return totalAmount;    
  9. }    
  10.     
  11. private int CalculateVAT(int transactionAmount)    
  12. {    
  13.     .....    
  14.     // does some calculations and returns an integer value    
  15. }    
Think of a situation where after six months or so the same developer comes back to modify the code as per the new business logic. Now, if I were that developer, the first question that I would have asked is that what is the type of transactionAmount? To figure that out I would have to check the type of the array, amounts. I would also have to verify the parameter type for the method CalculateVAT, and proceed accordingly.

This whole problem could have been solved, if the developer would have used int as a type instead of var while declaring the variable transactionAmount, in the first place. That would have made three things clear in an instant,
  • transactionAmount is an integer
  • the type of array amounts is also integer
  • the parameter expected by the method CalculateVAT is an integer
However, there can be one other scenario in which we change the type of amounts and type of parameter that CalculateVAT expects, to decimal. If the code is written as is, it would work just fine because we are using implicit type casting. But if we would have used an explicit type casting, declaring the variable as int, we would have been in trouble. We might face some exceptions and we definitely will have some data loss. Using a var saves us in such situations.

Anonymous Types and LINQ
 
One of the main reasons for introducing var was to provide an ease of development while working with Anonymous Types and LINQ. And often these two are used in conjunction. Let's see it in code:
  1. var groupedList = _paymentList.GroupBy(payment => new { PaymentId = payment.PaymentType })
  2.                       .Select(    
  3.                               g => new 
  4.                                    { 
  5.                                        PaymentTypeId = g.Key.PaymentId,
  6.                                        SumPaymentAmount = g.Sum(row => row.PaymentAmount) 
  7.                                    })    
  8.                       .ToList();    
  • Line 1 - we are grouping the _paymentList elements based on anonymous object.
  • Line 2 - we are now selecting each element and creating a new anonymous object using its properties.
  • Line 4 - we are now returning the collection of these new anonymous objects as a List.
If we wish to use explicit typing here, we need to create a new class and then use it instead of var. But what if the required object properties are changed and we need to return more/less data? Do we create a new class or our update the existing one? Well, the best alternative is to use anonymous type.

Since we are creating our object on the fly we cannot use static typing here. And, that's when var comes to our rescue. We declare the variable as an implicitly typed local variable by using var. The type name cannot be specified in the variable declaration because only the compiler has access to the underlying name of the anonymous type.

Summary

As per my understanding, we shall,
  • use var, while working with anonymous types.
  • use var, when the type of the declaration is obvious from the initializer, especially if it is an object creation. This eliminates redundancy.
  • if the code emphasizes the semantic “business purpose” of the variable and downplays the “mechanical” details of its storage.
  • use explicit types if doing so is necessary for the code to be correctly understood and maintained.
  • use descriptive variable names regardless of whether you use “var”.
  • variable names should represent the semantics of the variable, not details of its storage. For instance transactionAmount makes more sense to a reader than decimalAmount.
It would surely be great to receive any feedback on this topic. Please do share your opinion through comments.

Up Next
    Ebook Download
    View all
    Learn
    View all