0

I have two PictureBoxes where I want to show an image in the first and then a rotated version in the second. The code I would believe should work does act strange however, as the image is rotated in both PictureBoxes:

Image im = Image.FromFile(D:\somefolder\picture.jpg");            
pictureBox1.Image = im;
Image im_rot = im;
//Image im_rot = Image.FromFile(D:\somefolder\picture.jpg");
im_rot.RotateFlip(RotateFlipType.Rotate270FlipNone);
pictureBox2.Image = im_rot;

If I replace line 3 with line 4 it works, but why doesn't it work the other way?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Rado
  • 151
  • 2
  • 13
  • 2
    You should read about reference types vs value types. – Equalsk Oct 03 '17 at 20:22
  • Hm, OK, thought they were independent variables. Will look into this. Thanks! – Rado Oct 03 '17 at 20:50
  • Possible duplicate of [When I change the value of a variable which is a copy of another, it changes the original variable also](https://stackoverflow.com/questions/35395500/when-i-change-the-value-of-a-variable-which-is-a-copy-of-another-it-changes-the) – Sam Hanley Oct 03 '17 at 20:54

1 Answers1

3

The way your code is currently written, you're assigning the same object to both variables. This means that when you operate on either one, it's changing the same object in memory. With the alternate code you have commented out, you create a new, distinct object which is assigned to each variable.

Sam Hanley
  • 4,707
  • 7
  • 35
  • 63