Properties give you field like access while still protecting data with methods. This exists to simplify the pattern of creating private fields and public Get and Set methods:
class Line
{
private float _width;
public float Width
{
get => _width;
set => _width = value;
}
}
This defines a "property" Width. They are another type of member along with
fields and methods. They have their own accessibility level. It is typical to
use UpperCamelCase for properties. Properties do not require both the getter and
the setter.
Using properties
You can use this syntactic sugar which makes using properties just like using fields.
Line l = new Line();
l.Width = 5;
Auto-implemented properties
Many properties follow the form of simply getting and setting a value:
private float _width;
public float Width
{
get => _width;
set => _width = value;
}
This can be shortened to the following without even needing to define the backing field:
public float Width { get; set; }
The compiler will generate a backing field along with methods for using it. This field is no longer accessible, but that's rarely an issue. You can even give the field a starting value:
public string Name { get; set; } = "Player";
Object initializer syntax
There's a special syntax for setting an objects properties when initializing an object (without using a constructor):
Circle circle = new Circle() { Radius = 3, X = -4 };
public class Circle
{
public float X { get; set; } = 0;
public float Y { get; set; } = 0;
public float Radius { get; set; } = 0;
}
You cannot use this syntax with get only / immutable properties:
Circle circle = new Circle() { Radius = 3, X = -4 };
circle.X = 2; // This line fails to compile, but the above initialization works.
public class Circle
{
public float X { get; init; } = 0;
public float Y { get; init; } = 0;
public float Radius { get; init; } = 0;
}