Search code examples
c#arrayspointersref

Is there a way to get a reference to a C# Array element?


I would like to know if there is a way to get a ref to an array element in c# .

Something like this but without the pointers :

SomeClass *arr[5];
...    
SomeClass** p = &arr[2];

So far I got this :

SomeClass arr[] = new SomeClass[5];
// Put something in the array
SomeClass p = arr[2]; // This will give me the initial object, not the array ref
p = new SomeClass(); // I want the array to now use this new object

Solution

  • Isn't this what you want?

    var arr = new SomeClass[5];
    ref SomeClass p = ref arr[2];
    p = new SomeClass();