Properties allow you to control access to variables of the variable, and is the recommended method of accessing object-oriented programming languages ​​such as C # outside variables. In our chapter in class, we first saw the use of the property, and the concept is quite simple. A property is like a combination of a variable and a method - it can not take any parameters, but you are able to process it in the property, there are two parts wrapped inside the property, one mill and one set method:
private string color;
public string Color
{
get { return color; }
set { color = value; }
}
Return method should return the variable, while the prescribed method should be assigned to a value. Our example is as easy as that easy, but it can be increased. Another thing that you should know about is the fact that only one method is required - either get or set, the second is optional. Allows you to define properties to read and write only, a good example of the usefulness of the properties is given here:
public string Color
{
get
{
return color.ToUpper();
}
set
{
if(value == "Red")
color = value;
else
Console.WriteLine("This car can only be red!");
}
}
Okay, we've made our property a bit more advanced. Color variables will now come back in uppercase letters, because before we return it to the ToUpper() method, and when we try to change it, only " Red "value will be accepted. Of course, this example is not terrible useful.