var i = new int[2];
Is "i" considered to be boxed?
No there is nothing to box. The var keyword doesn't mean that the variable is boxxed. It doesn't do any conversion during the runtime. The var keyword is strictly a C# construct. What is actually happening when you use var is:
var i = new int[1];
IL sees it as:
int[] i = new int[1]
Now if you are asking if when you assign an int to part of the array of i does it box?
such as:
i[0] = 2;
No it does not.
This is opposed to which does:
var o = new object[1];
o[0] = 2;
This example does and why using ArrayList (think expandable array) in 1.0, 1.1 (pre generics) was a huge cost. The following comment applies to the object[]
example as well:
Any reference or value type that is added to an ArrayList is implicitly upcast to Object. If the items are value types, they must be boxed when added to the list, and unboxed when they are retrieved. Both the casting and the boxing and unboxing operations degrade performance; the effect of boxing and unboxing can be quite significant in scenarios where you must iterate over large collections.
MSDN Link to ArrayList
Link to Boxing in C#
Assuming this is C# (var
and C#-like array syntax), no, i
is not boxed. Only primitive value types (think numeric values) can be boxed.
The values in the array are not boxed either, since values in primitive arrays do not get boxed.
Array in C# is referential type so there's no need for boxing. You will however have boxing in this example:
var i = 123;
object o = i;
Boxing only occurs when a value type (i.e. a primitive type, struct or enumeration) is being treated as a reference type. Your array is declared to hold values of type int
. The var
keyword merely tells the compiler to infer the type of variable i
, rather than you having the specify it manually.
Had you written:
var i = new object[2];
The compiler would translate that to object[] i = new object[2]
, and any int
values you put in there would be boxed. Any reference type you put in the same array would not need any boxing.
In short, var
has nothing to do with boxing.
Here's a diagram of different types in .NET. You might also want to read .NET Type fundamentals.
精彩评论