2

I am having trouble creating an alias for a member of a struct array. Usually when the array members are of reference type, I create a reference to the member's reference as follows:

CustomReferenceType[] foo = new CustomReferenceType[10];
CustomReferenceType alias=foo[0];

Attempting to do something like that to an array with value type members, the compiler copies the value itself to the new variable, so for instance, when I manipulate the members of my struct, the changes are not reflected back to the original struct.

Is there a way to alias value type members without boxing/unboxing?

Saloom
  • 163
  • 10

1 Answers1

2

No, there is no way to create a reference to a value type.

Apart from a situation when you pass a value object by reference to a method, C# does not offer a way to make references to value objects. You need to set the actual object inside your array in order to make its value change.

Note: Since structs should generally remain immutable, creating references to them should not be required.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Thanks! In fact, I will convert the objects to classes. Actually there was absolutely no reason of using a struct. I can recall doing so, because half of my project is located inside a PIC Microcontroller where I had to use structs all the time. Power of habit. Thanks for the nice link though, I will keep it in mind for the future! – Saloom Jan 17 '16 at 15:57