0

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?

asked Aug 29, 2014 at 3:28
2
  • Is this your own Point struct, or is it System.Drawing.Point? Commented Aug 29, 2014 at 3:33
  • @Blorgbeard It's System.Drawing.Point Commented Aug 29, 2014 at 3:39

2 Answers 2

5

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.

answered Aug 29, 2014 at 3:41

Comments

1

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

answered Aug 29, 2014 at 3:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.