tags:

views:

66

answers:

3

The question is: at the end of this code the value of ptArray[0].X is 3.33 or 1.11?

Thanks.

class MyPoint
{

  public double X, Y;

  public MyPoint(double x, double y)
  {
     X = x;
     Y = y;
  }
}

MyPoint[] ptArray = new MyPoint[2];

ptArray[0] = new MyPoint(1.11, 2.22);

MyPoint first = ptArray[0];

// Am I changing ptArray[0] here or not?
first.X = 3.33;
first.Y = 4.44;
+5  A: 

You're not changing ptArray[0] itself, because that's a reference to the instance of MyPoint. However, you are changing the data within the object that it's referring to. So if you do:

first.X = 3.33;
Console.WriteLine(ptArray[0].X);

it will indeed print out 3.33.

Note that this wouldn't be true if MyPoint were a struct instead of a class. Although having mutable structs is a whole other realm of pain...

Jon Skeet
A: 
3.33

because your MyPoint is classs unlike standard Point which is struct

Andrey
A: 

You can try executing your code and print the output of ptArray[0] to console.

Try this

Console.WriteLine(ptArray[0].X + " " + ptArray[0].Y);

Then you will see it is changed to 3.33, 4.44

djerry