开发者

Difference between properties and variables

开发者 https://www.devze.com 2023-01-27 18:25 出处:网络
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 bec
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?


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消