Properties
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.
Having problems with this chapter? Ask in our forums!
© net-tutorials.com 2006 - 2010