17.1. Properties
An object's attributes can be accessed directly (if they are declared public) or through get and set methods (accessors and mutators). These methods provide a single point of access to the attributes. You can change the implementation of these methods without affecting the code that calls them. C# provides the property construct, which makes the calling of these get and set methods transparent to the end user.
A property is typically used to model simple attributes. For example, you can set or get the color of a car (an object) using both properties and methods, as shown next. Using properties:
1) car.Color = "red"; 2) string color = car.Color;
Using method calls:
3) car.SetColor ("red"); 4) string color = car.GetColor(); ...
Get .NET for Java Developers: Migrating to C# now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.