Jack Mariani
Jack Mariani

Reputation: 2408

How can I access an indexer by reference

I've created one class with an indexer.

public class IntArray
{
        protected int[] _thisArray = new int[20];

        // --------------- ARRAY --------------- //
        public int this[int index] { get => _thisArray[index]; }
}

Now I want to access the indexer by reference. This is what I tried:

private void AccessWithReference()
{
        var intArray = new IntArray();
        SetByReference(ref intArray[0]);
}

private void SetByReference(ref int value) { value = 0; }

But I get an error. On the other hand, if I try to access directly the array ref _thisArray[0] everything is fine. How can I access an indexer via ref?

Upvotes: 0

Views: 226

Answers (1)

Marco Aguilar
Marco Aguilar

Reputation: 90

The Microsoft docs says "An indexer value is not classified as a variable; therefore, you cannot pass an indexer value as a ref or out parameter."
You could use a temporary variable to make this work, like this:

private void AccessWithReference()
{
   IntArray intArray = new IntArray();
   int a = intArray[0];
   SetByReference(ref a);
}

An Indexer is a reference type already

Upvotes: 1

Related Questions