I have a structure that describe points:
public struct Point
{
int _x;
int _y;
#region properties
public int X
{
get { return _x; }
set { _x = value; }
}
public int Y
{
get { return _y; }
set { _y = value; }
}
#endregion
}
A lot of points are instantiated and stored in several Lists. Sometimes I have to change some Points and because to know in which List are stored the Points can be tricky, I wanted to create a List with all the Points instances thinking that a change in this list would affect other lists.
To be clear below some code to explain what I wanted to do:
List<Point> lstAllPoints = new List<Point>() { };
List<Point> lst1 = new List<Point>() { };
List<Point> lst2 = new List<Point>() { };
//some points are generated and stored in a list
for (int i = 0; i < 10; i++)
{
Point pt = new Point();
pt.X = i;
pt.Y = i + 1;
lstAllPoints.Add(pt);
lst1.Add(pt);
}
//some other points are generated and stored in another list
for (int j = 0; j < 10; j++)
{
Point pt = new Point();
pt.X = j;
pt.Y = j + 3;
lstAllPoints.Add(pt);
lst2.Add(pt);
}
Now my idea was to say if I change a Point in lstAllPoints then the corresponding point in others lists will be changed.
lstAllPoints[0].X = 400;
lstAllPoints[10].X = 800;
then: lst1[0].X is egal to 400, and lst2[0].X is egal to 800;
But because Point in this case is a structure in a list the reinitialisation "lstAllPoints[0].X = 400" does not work and because struct are value type the instances lstAllPoints[0] and lst1[0] are not the same instance: a change in lstAllPoints will not affect the Points in other lists.
The workaround I used was to change struct to class. A Point is then a reference type and everything works... perfect.
My question is: Is changing struct to class the only workaround? Are there no solutions to fill lists with the instance of the same struct instance, in such a way that changing a Point in a list change all other Points that share the same instance?
I think boxing/unboxing are not useful. I thought of pointers but then I have to work in an unsafe context and I don´t want to. I thought of using the keyword ref but it can only be applied to methods parameters:
//someting like
List<ref Point>...
Are there really no other solutions than changing struct to class?
Thanks in advance!
EDIT Here an edit to answer some of your comments. I am aware (or I guess I am aware) of the benefits of using struct in particular struct are put on the heap. Because I can have a lot of Points,it can be better to use structure in regards with performance concerns. I do not want to use pointer because I do not want to set an unsafe context. I do not have any reason not to use class. Nevertheless my question was more something for my culture because I was surprised not to be able to find a simple way to store a single struct instance in several lists.
Thank to all