When to Use ''Var'' as a Type

DZone 's Guide to

When to Use ''Var'' as a Type

There are two important ways of declaring data types in C# and .NET, 'var' and 'int'. Read on for a look at when to use each one.

· Web Dev Zone ·
Free Resource

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.


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 every line of code should be self-explanatory and developer-readable. Let's have a look at the below code:

public void SomeMethod()  
    // first approach - implicit type casting  
    var radius = 3;  
    var text = "some string literal";  

    // second approach - explicit type casting  
    int radius = 3;  
    string text = "some string literal";  

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).

CustomSaleInvoiceNumberService service = 
          new CustomSaleInvoiceNumberService(paramOne, paramTwo, paramThree);   
Dictionary<int, IEnumerable<Product>> stockProducts = 
          new Dictionary<int, IEnumerable<Product>>();    

// we can rewrite the above two lines using 'var', making them more readable  

var service = new CustomSaleInvoiceNumberService(paramOne, paramTwo, paramThree);  
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 latter lines of code did nothing magical expect that the two statements are more readable now.

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.


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 parameter to another method CalculateVAT. Notice, that the type of parameter that our method CalculateVAT expects is an integer. And that 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.

public decimal CalculateTotalAmount()    
    // some code here    
    var transactionAmount = amounts[2].TransactionAmount;    
    totalAmount = CalculateVAT(transactionAmount);    

    return totalAmount;    

private int CalculateVAT(int transactionAmount)    
    // does some calculations and returns an integer value    

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, 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 had 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 the array amounts is also an 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 typecasting, 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 easier development while working with Anonymous Types and LINQ. And often these two are used in conjunction. Let's see it in code:

var groupedList = _paymentList.GroupBy(payment => new { PaymentId = payment.PaymentType })
                              g => new 
                                       PaymentTypeId = g.Key.PaymentId,
                                       SumPaymentAmount = g.Sum(row => row.PaymentAmount) 
  • Line 1 - we are grouping the _paymentList elements based on an 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 an 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.


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 is indeed a debatable topic and I would love to know your opinion.

c#, data type, tutorial, var, web dev

Published at DZone with permission of Gaurav Gahlot , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}