Sunjue Li
Sunjue Li

Reputation: 27

Why I couldn't change the value of pictureBox1.Location.X directly?

I want to change the value of pictureBox1.Location. And the result really confuses me!

Point player;    
player = pictureBox1.Location;    
player.X += 10; //it works    
pictureBox1.Location.X += 10;//it doesn't work!! Why??    

so I try this one :

pictureBox1.Location = player // it works      

Could anyone tell me why? I only learnt c# for 1 week with head first c#, and I cannot find the answer through the Internet or the book.

Sorry, I didn't make my question clarified. I cannot build

pictureBox1.Location.X += 10    .

There is an error:

Cannot modify the return value of 'System.Windows.Forms.Control.Location' because it is not a variable

I want to know the difference between player.X and pictureBox1.Location.X

Upvotes: 0

Views: 105

Answers (2)

Yytsi
Yytsi

Reputation: 424

Messagebox also has, Left (R/W) Right (R) Bottom (R) Top (R/W)

R = Read only R/W = Read write

You can get the most right side of textbox coordinate x by typing

Int right_x = messagebox.Right;

Write

Messagebox.Left += 10;

and it works perfectly.

EDIT:

Source code of Messagebox.Location struct atleast has something like this.

Public struct Location { public int x, y; }

If you try this

messagebox.Location.x += 10;

You are trying to modify useless variable, and it's pointless. Now this is possible

Messagebox.Location = new Point(messagebox.Location.x + 10, messagebox.Location.y);

But the method I provided earlier is faster, since it doesn't care about y axis.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292385

Location is of type Point, which is a value type (struct). So when you access pictureBox1.Location, it returns a copy of the location. Changing X on this copy will have no effect on pictureBox1.Location, so it's probably not what you want; the compiler detects it and issues an error.

You must think of Point as a value, not an object that contains values. The fact that the X and Y property is unfortunate; writing mutable structs is a pretty bad idea, but Point dates back to the first version of .NET, and I guess MS had not yet realized how bad it could be...

Upvotes: 1

Related Questions