Properties

For security reasons, all the fields of a class shouldn't be exposed to the outside world. Consequently, exposing private fields is done by properties in C#, which are members of that class. Underneath the properties are special methods that are called accessors. A property contains two accessors: get and set. The get accessor gets values from the field while the set accessor sets values to the field. There is a special keyword for a property, named value. This represents the value of a field.

By using access modifiers, properties can have different access levels. A property can be public, privateread only, open for read and write, and write only. If only the set accessor is implemented, this means that the only write permission is given. If both set and get accessors are implemented, this means that both read and write permissions are open for that property.

C# provides a smart way of writing setter and getter. If you create a property in C#, you don't have to manually write setter and getter methods for a particular field. Consequently, the common practice in C# is to create properties in a class rather than creating fields and setter and getter methods for those fields.

Let's take a look at how to create property in C#, as shown in the following code:

class Animal {
public string Name {set; get;}
public int Age {set; get;}
}

The Animal class has two properties: Name and Age. Both the properties have Public access modifiers as well as setter and getter methods. This means that both properties are open for read and write operations. The convention is that properties should be camel case.

If you want to modify your set and get methods, you can do so in the following way:

class Animal {
public string Name {
set {
name = value;
}
get {
return name;
}
}
    public int Age {set; get;}
}

In the preceding example, we are not using the shortcut of creating setters and getters for the Name property. We have extensively written what the set and get methods should do. If you look closely, you will see the field name in lowercase. This means that when you create a property in camel case, a field with the same name is created internally, but in Pascal case. The value is a special keyword that actually represents the value of that property.

Properties are working behind the scenes in the background, which makes the code much cleaner and easier to use. It's very much recommended that you use properties instead of local fields.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.172.56