Properties
Properties allow you to control the accessibility of a classes variables, and is the recommended way to access variables from the outside in an object oriented programming language like C#. In our chapter on classes, we saw the use of a property for the first time, and the concept is actually quite simple. A property is much like a combination of a variable and a method - it can't take any parameters, but you are able to process the value before it's assigned to our returned. A property consists of 2 parts, a get and a set method, wrapped inside the property:
private string color;
public string Color
{
get { return color; }
set { color = value; }
}
The get method should return the variable, while the set method should assign a value to it. Our example is as simple as it gets, but it can be extended. Another thing you should know about properties is the fact that only one method is required - either get or set, the other is optional. This allows you to define read-only and write-only properties. Here is a better example of why properties are useful:
public string Color
{
get
{
return color.ToUpper();
}
set
{
if(value == "Red")
color = value;
else
Console.WriteLine("This car can only be red!");
}
}
Okay, we have just made our property a bit more advanced. The color variable will now be returned in uppercase characters, since we apply the ToUpper() method to it before returning it, and when we try to set the color, only the value "Red" will be accepted. Sure, this example is not terrible useful, but it shows the potential of properties.
No comments:
Post a Comment