Sergey
Sergey

Reputation: 49728

Difference between properties and variables

class MyClas
{
   public System.Windows.Point p;
   public void f()
   {
      p.X = 0;
   }
}

This code works perfectly.

At the same time this one causes compilation error ("Cannot modify the return value of p because it is not a variable"):

class MyClas
{
   public System.Windows.Point p {get; set;}
   public void f()
   {
      p.X = 0;
   }
}


What's the difference?

Upvotes: 2

Views: 339

Answers (1)

CodesInChaos
CodesInChaos

Reputation: 108790

You're using a mutable struct which is evil.

Your problem is that a property returns a copy of the struct, and not a reference to the original field. So your modifications would only affect the copied struct.
In some simple cases(calling setters) the compiler catches your mistake. In complex cases(calling of a method which mutates the struct) the compiler doesn't catch it and your code will silently fail(i.e. the copy gets modified and the original remains unchanged).

The workaround is using p=new Point(x,y)

Upvotes: 7

Related Questions