Reputation: 4016
I was working on some C# code, and have 8 Points, which are being put into 6 Point arrays, each one with different combinations similar to the sample below:
Point pt10 = new Point(10,10);
Point pt20 = new Point(20,20);
Point pt30 = new Point(30,30);
Point[] ptArr1 = {pt10, pt20};
Point[] ptArr2 = {pt10, pt30};
I then noticed, that after initializing the Point arrays, changes to the Points were not reflected in the array, which tells me the arrays contain copies of the original Points, and not the Points themselves. Is this wasteful in terms of memory, and if so, is there a way I can make the arrays reference the Points, instead of copying the values?
Upvotes: 0
Views: 85
Reputation: 100630
Is this wasteful in terms of memory: no, it is cheaper to store small objects like Point
as value types (struct
) than reference types (class
). Size of reference type will include reference itself (8 bytes for x64), object header (8 bytes I think) and data itself, when for value types there is just cost of values.
Notes
Upvotes: 1
Reputation: 43023
The behaviour you observe happens to structs in C# and is because:
Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary. (source)
If you want to have a reference to the points stored in your array so that changes in the variable are reflected in the array, you should use a class for points, not a struct.
Upvotes: 5