Understanding Property in C#

  • Property is a flexible mechanism to read/write/manipulate the private field of your class. Properties are access like a public field of class but actually Properties are special kind of methods called accessors.
  • Property enable accessing data easily and safely.

In this post i write down a Student class contains two property called name and age, and let us assume a business scenario in which,

  • You can not change the Age once after instantiation.
  • You can change the Name even after instantiation.

This is a simple example for property in C#:

Here Age is property, and _Age is private field and this is called backing field. which is actually holding the value.

Properties have two backing methods – get/set.

You can apply access specifiers like public,private,protected,internal to enable/restrict accessibility of the property. Suppose I do not want any body to set the Age value outside of the student class I can make the “Set” accessor as private. So that no body can assign value outside of the student class.

The program try to access the property “Age” which is private, so the compiler will not compile the program, instead it will throw the exception.

Error CS0272 The property or indexer ‘Student.Age’ cannot be used in this context because the set accessor is inaccessible

So you can’t able to assign value to the property with private set, similarly you can use different access specifiers on the properties get/set method.

0 comments… add one

Leave a Comment