I have always thought it was "best practice" to be explicit in naming my collection variables. So, if I had a collection of Car objects, I would typically name a Car[]
carArray
and a List<Car>
carList
.
And then 99% of the time, I end up just doing something like...
foreach (Car car in carArray)
{
...
}
...and I'm thinking, I could have just called the array cars
, and it wouldn't have made any difference.
And now that we have IEnumberable<T>
, I'm actually faced with the question of whether I might considering writing something like carIEnumerable
? or carEnumerable
. So far, the answer has been "no".
My thinking here is that the type of collection often doesn't matter, and when it does, is still doesn't matter if the collection type is written into the variable name. I just had a case where I had to switch from an IEnumerable<Car>
to a List<Car>
because I needed "bracket access" to the items (e.g., carList[3]
). In that case, the two collection types do not behave the same, but would naming the variable cars
have been a problem here?
Not to add another layer of complexity to this question, what happens if I use var
? E.g.,
var cars = GetCars();
I can certainly tell cars
is some kind of collection. I can iterate it. If I'm using LINQ, I can use extension methods. More importantly, if I later change up the type of collection, there would be much less code to mess with. var
would still be var
and cars
would still be cars
. That seems very appealing to me, and I having trouble seeing much disadvantage.
So, just to make sure my question is clear: How do you name your collection variables and why? Is there a serious readability or clarity cost to just "pluralizing" the name of the item?
Thanks.