What are array indices?

I know that indexers List<T>, for example, resemble properties. Taken from msdn:

Indexers allow you to index instances of a class or structure just like arrays . Indexers resemble properties, except that their Parameters.

But I can’t understand why the following happens:

int[] myArray = new int[0];
List<int> myList = new List<int>();

Interlocked.Increment(ref myArray[0]);  // fine

Interlocked.Increment(ref myList[0]);   //CS0206    A property or indexer may not be passed as an out or ref parameter

Shouldn't they work the same way?

+4
source share
2 answers

The indexer for List<T>allows you to access elements using properties (Methods), which makes it look like an array. You cannot pass the generated method refas if you wrote:

Interlocked.Increment(ref myList.GetItem.get_Item(0));

. CLR. array[i] , ref.

#:

, , . , ref out.

List<T> ( ):

public T this[int index]
{
    get
    { // some checks removed 
        return _items[index];
    }

    set { _items[index] = value;}
}

IL :

IL:

IL_0014: ldelem.i4

List :

IL_001b:  callvirt   instance !0 class [mscorlib]System.Collections.Generic.List`1<int32>::get_Item(int32)

, #. .

+7

, , , . , () , . DID , , . :

public class Foo {
        public int this[int x] {
            get {
                return 1;
            }
            set {
                //meh. whatever. 
            }
        }
    }

Foo[0] out, ? . ref out.

+4

All Articles