An array indexer attribute returns an object - is it inserted?

I came across the fact that indexer this[int index] { get; } this[int index] { get; } works differently for an array of structures than for a list of structures. Namely, that the indexer in the case of T[] returns a reference to the element inside the array, while the indexer in the case of List<T> returns a copy of the element.

This is a very big semantics and performance difference, and I'm glad that T[] allows you to bypass the performance limitation of List<T> .

However, I am puzzled by the actual implementation. The code for Array in .net source reads this way:

 Object IList.this[int index] { get { return GetValue(index); } set { SetValue(value, index); } } 

Where GetValue is defined as follows:

 public unsafe Object GetValue(int index) { if (Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_Need1DArray")); Contract.EndContractBlock(); TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 1, &index); return TypedReference.InternalToObject(&elemref); } 

The return type of the Object indexer, implying that boxing will take place.

So my question is: can I be sure that no boxing will happen when I get access to the element T[] , where T is a structure?

I assume that the compiler and / or CLR are specific to the array, and in fact the signature of the indexer does not bother. It's right? Is there a more complete discussion of this somewhere?

+5
source share
1 answer

Namely, that the indexer in the case of T [] returns a reference to the element inside the array

Not really. Moreover, there is no indexer for arrays - instead, the access element expression represents access to the array instead of access to the element (sections 7.6.6.1 and 7.6.6.2 of the C # 5 specification, respectively).

There is a very important difference between the two - in particular, array access is classified as a variable, while indexer access is classified as a value.

It is very similar to the difference between a property and a field - they both have the same syntax for access, but the property calls the function element and returns a value, while access to the field gives only a variable.

So my question is: can I be sure that no boxing will happen when I get access to the element T[] , where T is a structure?

If you use it as T[] , be sure. The pointer you were looking at is used only when you are viewing the array as an IList . Therefore, if you use:

 IList array = new int[2]; object x = array[0]; 

then yes, it will be useful value ... but if you write

 int[] array = new int[2]; int x = array[0]; 

it will not, and it will not access this indexing code or GetValue method at all.

+9
source

All Articles