1

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
4
  • If SomeClass is a reference type, then you have a reference to the object at arr[2], and changing a property of p will change the same property in arr[2]. Commented Apr 10, 2021 at 4:07
  • I will edit the question to explain the problem a bit better Commented Apr 10, 2021 at 4:08
  • There is no way to do that without pointers Commented Apr 10, 2021 at 4:11
  • Why do you want to make this a field? Sounds like an XY problem. If you just want a way to "get and set a SomeClass", you can store a Func<SomeClass> and Action<SomeClass> instead. Commented Apr 10, 2021 at 4:19

1 Answer 1

4

Isn't this what you want?

var arr = new SomeClass[5];
ref SomeClass p = ref arr[2];
p = new SomeClass();
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, but is there a way to declare p as a member variable ?
@AntoineGagnon That's quite an unsafe thing to do, so you have to use pointers.
@AntoineGagnon ref exist in the stack. This is how C# ensure the lifetime. Although, you can make the array a field, then take the ref every time you need it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.