I'm looking at the upcoming Visual Studio 2017.
Under the section titled Boosted Productivity there is an image of Visual Studio being used to replace all occurrences of var with the explicit type.
The code apparently has several problems that Visual Studio has identified as 'needs fixing'.
I wanted to double-check my understanding of the use of var in C# so I read an article from 2011 by Eric Lippert called Uses and misuses of implicit typing.
Eric says:
- Use var when you have to; 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; “decimalRate” is bad; “interestRate” is good.
I think most of the var usage in the code is probably ok. I think it would be ok to not use var for the bit that reads ...
var tweetReady = workouts [ ... ]
... because maybe it's not 100% immediate what type it is but even then I know pretty quickly that it's a boolean
.
The var usage for this part ...
var listOfTweets = new List<string>();
... looks to me exactly like good usage of var because I think it's redundant to do the following:
List<string> listOfTweets = new List<string>();
Although based on what Eric says the variable should probably be tweets rather than listOfTweets.
What would be the reason for changing the all of the var
use here? Is there something wrong with this code that I'm missing?
var
here are fine. You could possibly change one - but even then I think it isn't really necessary. Why change them all to explicit type?vars
have been marked in the same way; with the same cautionary cross mark next to them and a red underline. Presumably Visual Studio wants to correct them all in the same way. Unless I am mistaken.