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),
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.
- public decimal CalculateTotalAmount()
- {
-
- .....
- var transactionAmount = amounts[2].TransactionAmount;
- totalAmount = CalculateVAT(transactionAmount);
-
- return totalAmount;
- }
-
- private int CalculateVAT(int transactionAmount)
- {
- .....
-
- }
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:
- 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
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.