Properties in C#

Attributes allow you to control the access to the variables of the classes, and is the recommended way to access variables from outside in Object Oriented programming languages ​​like C #. In our chapter on class, we first saw the use of a property, and the concept is actually very simple. A property is similar to a variable and a method - it can not take any parameters, but you can not take any parameters before returning Are able to process. A property wrapped inside property consists of 2 parts, one mill and one set method:

private string color;

public string Color
{
    get { return color; }
    set { color = value; }
}
The return method should return the variable, while the set method should give it a value. Our example is as easy as it is, but it can be extended. You should know one more thing about the qualities, the fact is that only one method is needed - either get or set, the second is optional, it is to define the read-only and write-only properties Here's a better example of the usefulness of the properties:

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 return to uppercase letters, because we apply the ToUpper () method before returning it, and when we try to set the color, only the "red" value will be accepted. Of course, this example is not terrible useful, but it reflects the potential of properties






Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment