0

this might seem silly, so please excuse my naivety.

If I had an integer, say int counter = 2; then I could create integer int anotherCounter = counter; and if I were to print the value of anotherCounter, it would obviously return 2.

Now, if I then said anotherCounter = 5; then this would not change the value of our first value, counter. Likewise, if I changed the value of counter to counter = 10;, then that wouldn't affect anotherCounter.

However, I've created a class that I have used to instantate some objects, but if I do what I just described to my objects, they all seem to share the same values:

HSVImage initial = new HSVImage(1920, 1080);
HSVImage duplicate = initial;

For some reason, if I now change anything in duplicate, then it also affects intial. Can someone explain where I've gone wrong? I assume it's to do with how I set up my HSVImage Class?

Thank you. Sam

Sam Stenner
  • 15
  • 3
  • 12
  • In addition to answers below, if you want to achieve similar behavior of your HSVImage class as it's value type, consider change it from class into struct which is value type. – Darjan Bogdan Jan 08 '17 at 17:40

2 Answers2

1

That's because objects are passed and copied by Reference unlike primitives that are being passed by Value.

When you write

HSVImage initial = new HSVImage(1920, 1080);
HSVImage duplicate = initial;

you will copy the Reference to initial into duplicate which means that initial will now point at the same object as duplicate

on the other hand, when you write

int counter = 2;
int other = counter;

you will place the Value of counter inside other.

You can read more about it here: https://msdn.microsoft.com/en-us/library/0f66670z.aspx

gkpln3
  • 1,317
  • 10
  • 24
  • Hi, thanks for that! I understand what you mean by this, but I still don't know how to fix my problem. How do I go about making my duplicate a value instead of a reference? In the documentation it says that I'd have had to put 'ref' in the parameters, but I haven't, so why does it think it's a reference? – Sam Stenner Jan 08 '17 at 17:47
  • You can use the **Copy constructor** `HSVImage initial = new HSVImage(1920, 1080); HSVImage duplicate = new HSVImage(initial);` This will create a new object with the same attributes as the first one. – gkpln3 Jan 08 '17 at 18:12
  • Ah right, thank you so much! – Sam Stenner Jan 08 '17 at 19:54
0

No, it's not part of your HSVImage class setup, it's how .Net framework handles reference type which is object of HSVImage class as oppose to value type which is your counter variable. Please read more about the topic at the following link https://msdn.microsoft.com/en-us/library/t63sy5hs.aspx

Darjan Bogdan
  • 3,780
  • 1
  • 22
  • 31