c# - Array indexer signature returns object - does it box? -
i stumbled on fact indexer this[int index] { get; }
works differently array of structs list of structs. namely, indexer in case of t[]
returns reference element within array whereas indexer in case of list<t>
returns copy of element.
this big semantic , performance difference, , i'm glad t[]
allows work around performance limitation of list<t>
.
however, i'm puzzled actual implementation. code array
in .net reference sources reads thus:
object ilist.this[int index] { { return getvalue(index); } set { setvalue(value, index); } }
where getvalue
defined 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 indexer object
, implying boxing take place.
so question is, can no boxing occur when access element of t[]
t
struct?
i assume compiler and/or clr treat array specially, , don't bother signature of indexer. correct? there fuller discussion of somewhere?
namely, indexer in case of t[] returns reference element within array
not really. it's more there isn't indexer arrays - instead element-access expression represents array access instead of element access (sections 7.6.6.1 , 7.6.6.2 of c# 5 spec respectively).
there's significant difference between these 2 - in particular, array access classified variable, whereas indexer access classified value.
it's similar difference between property , field - both have same syntax access, property invokes function member , returns value, whereas field access yields variable.
so question is, can no boxing occur when access element of
t[]
t
struct?
if you're accessing as t[]
, sure. indexer looked @ used when you're viewing array ilist
. if use:
ilist array = new int[2]; object x = array[0];
then yes, that'll box value... if write
int[] array = new int[2]; int x = array[0];
then won't, , won't accessing indexer code or getvalue
method @ all.
Comments
Post a Comment