You don't need to use set or get. You could write functions named setFoo or getFoo instead of using a property Foo:
But that's a real pain -- you'd rather write
So instead C# has properties:
Inside the setter, the keyword 'value' is the variable containing the value that is getting assigned to the property Y.
The pattern of having properties directly backed by fields is so common that in C# 3, shortcut syntax was added.
There are a few reasons to use properties, instead of public fields. One is that properties can be virtual. Another is that you can make the setters for a property private. Another is that properties have a 'special' meaning to things that inspect classes at runtime. There are frameworks for conveniently talking to databases and for reading and writing objects to and from XML and all sorts of other things -- and they automatically look at the object's properties (and not private fields or other things) to see how to do their job.
class Point {double x, y;public Point(double x, double y) {this.x = x;this.y = y;}public double GetX() { return x; }public void SetX(double x) { this.x = x; }public double GetY() { return y; }public void SetY(double y) { this.y = y; }}
But that's a real pain -- you'd rather write
pt.Y = 3; and be able to write things like pt.Y += 5; , instead of pt.SetY(pt.GetY() + 5); .So instead C# has properties:
class Point {double x, y;public Point(double x, double y) {this.x = x;this.y = y;}public double X {get { return x; }set { x = value; }}public double Y {get { return y; }set { y = value; }}}
Inside the setter, the keyword 'value' is the variable containing the value that is getting assigned to the property Y.
The pattern of having properties directly backed by fields is so common that in C# 3, shortcut syntax was added.
class Point {public Point(double x, double y) {X = x;Y = y;}public double X { get; set; }public double Y { get; set; }}
There are a few reasons to use properties, instead of public fields. One is that properties can be virtual. Another is that you can make the setters for a property private. Another is that properties have a 'special' meaning to things that inspect classes at runtime. There are frameworks for conveniently talking to databases and for reading and writing objects to and from XML and all sorts of other things -- and they automatically look at the object's properties (and not private fields or other things) to see how to do their job.