Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a reference to a list c# struct

Tags:

c#

list

xna

I'm having a problem with BoundingSpheres in XNA. I'm wanting to add a BoundingSphere to a list of BoundingSpheres. At the moment it's along the lines of:

Aircraft(Vector3 pos, float radius, CollisionManager colMan)
{ 
    BoundingSphere sphere = new BoundingSphere(pos, radius);
    colMan.AddSphere(sphere)
}


List<BoundingSphere> spheres = new List<BoundingSphere>();

CollisionManager()
{
    spheres = new List<BoundingSphere>();
}

AddSphere(BoundingSphere boundingSphere)
{
    spheres.Add(boundingSphere);
}

Rather then a reference being added, it seems to be adding the values. I believe this is because boundingSpheres are structs? How can I get round this? I tried the ref keyword, but the values still aren't being updated in the list.

like image 279
Bushes Avatar asked Dec 08 '25 06:12

Bushes


1 Answers

To be straightforawrd, you can't, at least not directly. Structs are value types, and are thus passed and stored by value. Even judicious use of the ref keyword won't get around it because List<T>.Item can't return a reference to a value type.

The work-arounds are to either turn your struct into a class, or embed the stuct inside a class, or, just deal with the fact it's a value type and treat it appropriately (ie, don't try to modify local copies, but replace values in the list when the change). The last option is, imo, the best.

like image 175
Donnie Avatar answered Dec 10 '25 19:12

Donnie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!