References to Structs in an Array

  • Thread starter Thread starter Jose Ines Cantu Arrambide
  • Start date Start date
J

Jose Ines Cantu Arrambide

Hello,
I want to store references not values of MyStruct in an Array
(MyStruct[])... is it possible? How?

Thanks,
Jose.
 
You can use boxing concept of .Net here

Let's take a simple example you have structure POINT, then you can write following code to make it array of refernc

POINT[] aPoint = new POINT[10]; // declare array of structure, which is array of stucture values
Object aObject = new object[aPoint.Length]; // declares array of object reference

aObject = aPoint; // Box the structure value type to reference type, it becomes array of strcture reference

aObject[0].x = 3; //now aObject[0] is the reference of a structure

But remember, when you do above statement, actually it does not point to original structure values. So if you make changes to aPoint[0] = 10 ; then it will not be reflected in aObject[0] as aObject referes to different copy,which was created when we did aObject = aPoint
 
It all depends on where the stuct instances exist, heap or stack. If you
create them on the heap, you already have references to them; if you create
them on the stack, you *cannot* get references to them.

This creates them on the heap:

MyStruct[] a = new MyStruct[10];

for (int i = 0; i < 10; i++)
a.x = i;
 
Back
Top