Properties and Accessors C#
Blog > C# > Properties and Accessors C#

Properties and Accessors C#

PL

Properties and Accessors


Properties and accessors are so strongly correlated that it is impossible to discuss them separately. Property (called “Properties” – sometimes you can find the term derived from the English name “propercje” or shortened property) is a special construction, combining aspects of both fields and methods. It allows access to private variables of the object, through special methods being accessories. An important property is that the object user sees them as ordinary variables made public. They allow you to perform ordinary operations as on a variable, and also allow you to use them in interfaces.


Accessories are the equivalent of methods that have been used for a long time in object-oriented programming languages that allow reading and writing private class fields. Due to hermetization, all fields in the class should be hidden, and possible access to them is carried out through methods that additionally ensure control of the entered data. These methods are called “setters” and “getters”.


Contents


Accessors, a setters i getters


The syntax of the code using the setters and getters is presented below:


class Wartosci
{
  private int liczba;

  public int get_liczba()
  {
    return liczba;
  }

  public void set_liczba(int iLiczba)
  {
    liczba = iLiczba;
  }
}

The example seems convenient and consistent, but the methods are not interrelated, they can be in different places of the extended class, and in the case of many variables, it can grow into a lot of code lines. The use of such methods is as follows:


static void Main(string[] args)
{
  Wartosci wart = new Wartosci();

  //Setting values
  wart.set_liczba(12);

  //Reading values
  MessageBox.Show(wart.get_liczba());
}

Accessories perform exactly the same task, but using variables becomes more convenient. Below are the examples presented earlier with the use of accessors:


class Wartosci
{
  private int _liczba;

  public int liczba
  {
    get
    {
      //run when the value is read
      return _liczba;
    }
    set
    {
      //started when the value is set
      _liczba = value;
    }
  }
}

The code includes the get and set methods, they are equivalent to the methods from the previous example. In addition, these methods for the compiler actually arise. When you declare a property named number, the compiler has reserved the name of the methods get_liczba and set_liczba, so it is not possible to define them again, and the attempt will end with an error:


Type ‘Values’ already reserves a member called ‘get_number’ with the same parameter types


An interesting element of the property is the value keyword. It is a temporary variable that allows you to perform an operation on the currently entered value, eg when assigning the number = 10; the variable value will take the value 10.


Using the variable declared by the property looks like:


static void Main(string[] args)
{
  Wartosci wart = new Wartosci();

  //Setting values
  wart.liczba = 12;

  //Reading values
  MessageBox.Show(wart.liczba);
}

As it was mentioned at the beginning of the article, the operations take place as on the ordinary variable made available to the public.


Construction of properties


Properties can only have a value collection accessory, only value set accessories or both accessors at once. This allows to obtain variables with limited access – read-only, write-only or read-write variables. The get accessor always has to return the value via the keyword return.


The get accessor is started when the value is read, the accessor set when the value is set. All operations included in the accessor braces are then performed. Operations placed in the accessories should not be too complicated. In addition, an incorrect programming style is to change the value of a field in accessor get, eg:


public int Liczba
{
  get
  {
    return liczba++; //This should not be used
  }
}

The property consists of only two elements: set and get, without the possibility to download parameters. Additional fields, methods and subsequent properties are not allowed. Properties must have at least one accessory.


Short declaration


Turning the usual methods into a property allowed to partially sort the code, but did not shorten it significantly. Because the commonly used accessors, as in the examples presented above, do not change the value, but only mediate access to it, a short declaration has been introduced (from version C# 3.0).


It allows you to reduce the following code:


class Wartosci
{
  private int _liczba;
  public int liczba
  {
    get
    {
      return _liczba;
    }
    set
    {
      _liczba = value;
    }
  }
}

in a very short entry:


class Wartosci
{
  public int liczba{get;set;}
}

Both entries are equal, because the compiler will develop a short declaration, and also implicitly create a private field, access to which the saved property performs. This allows to significantly shorten the record and increase the clarity of the code.


Summarizing. The record of the above abbreviated declaration named liczba implicitly creates a private variable and methods named get_linary () and set_number () allowing access to the variable value.


Operators and properties


Properties, in contrast to the usual methods, also allow operators to use read and write values simultaneously. These operations work without creating additional declarations. The following are operations on the values from previous examples and information on which accessor was started:


static void Main(string[] args)
{
  Wartosci wart = new Wartosci();

  int m = wart.liczba; //Block get for values
  wart.liczba = m; //Block set for values
  wart.liczba -= 12; //Block get i set for values
  wart.liczba += 18; //Block get i set for values
}

Value control (Properties and accessors)

Values of fields that have been made public are not controlled in any way. This can lead to serious errors in the functioning of the class or even the entire program. The errors leading to the rapid spillage of the program are much better than long-lasting, failing to recognize the errors affecting the results. Finding such an error will require a lot of time and often to trace most of the written code. Simple examples of values that require control are: seconds / minutes (1-60), hours (1-12 / 1-24), grades (1-6), grades in studies (2; 3, 3.5; 4; 4, 5; 5) and many more. Example in code:


class Wartosci
{
  private int _godzina;

  public int godzina
  {
    set
    {
      if (value >= 1 && value <= 24)//for a 24-hour clock
      _godzina = value;
    }
  }
}

Controlling the entered values in the code that uses the class objects can lead to many undesirable effects. The code must be repeated in every place where data is entered, the programmer may forget about it or do it incorrectly, the class user may specifically lead to the write of incorrect values. The reasons mentioned are sufficient to ensure the correctness of the data being saved. An ideal place to control the entered values is the set accessory. It allows not only to define values in one easy to locate place, but also to quickly change the rules throughout the program, eg when the range of grades changes to 1-10.


Accessories have one more important function related to value control. The data read and written does not have to be a simple variable. What if we work with databases and data field is stored in such database? In this case, the get accessor can carry out a given value, and the set accessor checks whether the value matches the field type in the database and the entry when it is correct. For a programmer using a class, it is not important to connect to the database, he sees the value just like a simple variable. Working on a common code by many programmers is also one of many reasons for using properties.


You can use other methods in the accessories. If the value checking is subject to the same conditions as in the case of seconds and minutes, it is possible to prepare a method that checks the values and later uses them in the accessories.

What to use properties for?


If I have not yet convinced you to use the properties, I will give you two more examples.


Example 1:


Assume that the variable (int type) in the class is the result of the operation, and its value is part of the name of the file being saved. After the changes made to the program, it is necessary to add the prefix in the name in the form:


"wyniki_" + zmienna.ToString();

Changing the naming in the whole program can take a lot of time, and there is always the danger of missing a value. Using the properties from the beginning, the whole operation would be limited to one change in Access get.


Example 2:


In the running program, it was necessary to count the number of changes introduced in the “number” variable. To implement this functionality, all the places where the variable “number” will receive new values and increase the counter in them should be found. Applying properties allows you to do this by supplementing the accessor set with an additional line:


licznik++;

Technical aspects of properties and accessors


  • Properties can have access modifiers: public, private, protected and internal. Both accessors can have different access modifiers. Thanks to such an application, the readout of the variable can be public, hence available from outside the class, and the record of its private or protected value.
  • Properties can be static, declared using the static keyword. Thanks to this, the property is available even without an instance of a class – object.
  • Properties can be virtual, declared using the virtual keyword. This allows you to change the behavior of properties in derived classes through the override keyword.
  • Properties can not be const, because there is no need. In addition, methods, properties and events are not supported in C #.
  • Properties are not variable, so it is not possible to pass them through ref or out keywords. This is completely justified because the property as a set of methods does not represent a specific place in memory.
  • The property allows for the establishment of breakpoints, which is understandable, because these are normal methods for the compiler.
  • Properties can be placed in interfaces – these are methods, fields in interfaces are prohibited. Property accessories can not have implementation in the interface, therefore their entry ends with a semicolon: get; and set;
  • Abstract properties exist only in abstract classes.

Advantages of properties


To sum up the advantages of using properties, the following can be mentioned as the main ones:


  • Code transparency.
  • Admission of a shortened record – summary declaration.
  • Encapsulation of the code.
  • Interface compatibility.
  • Comfortable management of the application.
  • Validation of variable values.
  • Operating on methods just like on a regular variable, using operators +, -, =, + =, – = …
  • Many others providing convenience, security and shortening the code.

×
Any questions?
TOP