Iterating through an object array; foreach(var... vs. foreach(object
Solution 1
From a purely functional perspective, var
is just a shortcut for object
here, since objArray
's elements are of declared type object
.
Using object
is a sign to whoever's reading the code that the items in the array are not known to be any type more specific than object
. The use of var
does not connote this. In the minimal case you posted, it really doesn't make any difference to the clarity of the program which one you use.
If, on the other hand, it is not immediately clear from the context what type of object you are working with, then it may be advantageous to explicitly declare the type. On the other hand, if the type of the elements of the collection you're iterating over is verbose and obtrusive, then it may be advantageous to use var
, so that the reader's eyes will be drawn to the logic of the code rather than a mess of generic parameters.
Solution 2
The only difference between var
and any other type is that you let the compiler determine the type.
Solution 3
In your example no. But,
When declaring objects
you get:
Boxing and Unboxing
However. When using var, it is compiled exactly as if you specified the exact type name.
So var tempval = 5;
is the same as int tempval = 5;
Solution 4
there is no difference between those two, var
would be object
in this case.
user943870
Updated on June 05, 2022Comments
-
user943870 over 1 year
object[] objArray = new object[]{"blah", 4, "whatever"}; foreach(var value in objArray) vs. foreach(object value in objArray)
I'm curious as to what the difference is between those, other than var must remain its type after assigned. Is one better than the other? Thanks.
-
user943870 over 11 yearsThanks for the clarification.