faster way between to ways of iterating through all the elements of a collection in C#
c#, foreach
Solution
They're both exactly the same. `var` is syntactic sugar for convenience. It makes no difference to the speed with which a `List` is traversed.
The rule of thumb I follow with `var` is to only use it if the type of the object is present on the right-hand side of an assignment, so in this case I'd prefer to explicitly specify the type in the `foreach` to make it clearer for other engineers, but it's down to personal choice. If you hover over a `var` in Visual Studio, it will display the type (assuming it can infer what is should be).
Problem
The language I use is C#. Let we have a List of objects of type `T`, ``` List<T> collection = new List<T>{.....}; ``` Say that we want to go over each item of collection. That can be done in many ways. Among of them, are the following two: ``` foreach(var item in collection) { // code goes here } ``` and ``` foreach(T item in collection) { // code goes here } ``` Does the second way be better than the first or not and why? Thanks in advance for your answers.