Enforcing encapsulation

Previously, we went through the following concepts in Chapter 2Understanding Classes, Structures, and Interfaces, and  Chapter 3Understanding Object-Oriented Programming:

  • Accessing modifiers and how they help us to control access to methods and fields in the same class, in the same assembly, and in the derived classes
  • Encapsulation and how it helps us to group together related fields and methods together in the same object

However, there is another concept in encapsulation called properties, which makes sure that no one can have direct access to the data fields outside the class. This helps us to make sure that we have control over the modification of the data fields. 

A property is very similar to the field of a class. Just like the field of a class, it has a type, name, and access modifier. However, what makes it different is the presence of accessors. Accessors are the get and set keywords that allow us to set and retrieve values from a field.

The following is what the syntax of a property looks like:

class SampleProperty
{
private string name;
public string Name
{
set { if(value != null)
{
this.name = value;
}
else
{
throw new ArgumentException();
}
}
get { return this.name; }
}
}

In the preceding code, please note the following:

  • For the SampleProperty class, we have declared a name field and a Name property.
  • The name field has been marked private, hence it won't be accessed outside the SampleProperty class.
  • The Name property has been marked public and has the get and set accessors.
  • In the set method, we are checking whether the value passed is null or not. If it's null, we are raising an argument exception. Therefore, we are putting rules around the value that can be set on the name field.

In this way, properties help us in consume the fields of a class. 

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

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