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.
From a purely functional perspective,
varis just a shortcut forobjecthere, sinceobjArray‘s elements are of declared typeobject.Using
objectis a sign to whoever’s reading the code that the items in the array are not known to be any type more specific thanobject. The use ofvardoes 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.