Contents

When to use 'var' as a Type?

It has been quite a long time since var was introduced, yet it stands debatable among .Net developers. Everyone has a different understanding as and when to use var as a type. A couple of days ago I was also a part of one such discussion, and so I decided to share my understanding.


Readability

Every developer has all the right to use var as and when they like, it’s just a matter of one’s choice. However, I think, sometimes it’s good to use the actual types rather than var.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public void SomeMethod()
{
    // first approach - implicit type casting
    var radius = 3;
    var text = "some value";

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

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 second 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 first one does the same. I do agree, but as I mentioned it’s just a matter of choice.

One of the many reasons why Microsoft introduced var is to make the code more readable and help developers write clean code. For example, see the code below:

1
2
3
4
5
6
7
8
ThisIsABigClassName tempVariable = new ThisIsABigClassName(paramOne, paramTwo, paramThree);
Dictionary<int, IEnumerable<Product>> stockDictionary = new Dictionary<int, IEnumerable<Product>>();

// the above two lines of code would be more readable, if we
// use var instead of the full class name as a reference type

var tempVariable = new ThisIsABigClassName(paramOne, paramTwo, paramThree);
var stockDictionary = new Dictionary<int, IEnumerable<Product>>();

In the above code we initialized a variable with an object using implicit type casting. It makes sense because the new keyword tells the reader that the variable is an object reference. Though the two statements do things differently, so it’s actually not a fair comparison. However, using var instead of an actual type in the above code, makes it more readable, clean and thus maintainable.

I think using a var is fine until and unless it does not hamper the meaning of the code. The reader shall be able to derive the semantics (what it does) of the code while looking at it, as in our code statement creating a new dictionary is equally understandable as the above. Rather in the above statement the type declaration serves as a distraction.


Maintainability

Assume a method CalculateTotalAmount, that uses an integer array amounts. The value at index 2 is 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
private decimal CalculateTotalAmount()
{
    // some lines of code here
    .....
    var transactionAmount = amounts[2].TransactionAmount;
    totalAmount = CalculateVAT(transactionAmount);

    return totalAmount;
}

// consider that the methods are arranged in the
// decreasing order of their accessibility, and so
// some other public/internal/protected methods here

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

When we use an anonymous type to initialize a variable, 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.

Also, using var is helpful while working with LINQ Expressions. It helps in scenarios when we (especially new developers) are not certain about the results that an expression would return.


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 Expressions. And often these two are used in conjunction. Let’s see it in code:

1
2
3
4
5
6
7
8
var groupedList = _paymentList.GroupBy(payment => new { PaymentId = payment.PaymentType })
                      .Select(    
                              g => new 
                                   { 
                                       PaymentTypeId = g.Key.PaymentId,
                                       SumPaymentAmount = g.Sum(row => row.PaymentAmount) 
                                   })    
                      .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 varcomes 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.


Conclusion

At this point I would highly recommend uses and misuses of implicit typing, a very well explained article by Eric Lippert.

  • Use var when you are using 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.
  • Consider using var 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.

Undoubtedly it’s an individual’s choice when to use var. However, through this post I just shared my opinion about the same. It would be great to receive any feedback on this topic. Please do share your opinion through comments.