C# Property

C# property is a member of a class that allows the class to expose some functionality without exposing the implementation details. This article explains what a property is in C#, why we need properties, and how to implement properties in C# and .NET.

I am assuming that you already know how to declare a variable and assign a value in a class. If you need more details, check out this free ebook - Beginning C# Object Oriented Programming.

In this article, I will answer the following three basic questions:
  • What property is
  • How can we implement a property
  • How do we use a property

 

Introduction


C# properties are members of a C# class that provide a flexible mechanism to read, write or compute the values of private fields, in other words, by using properties, we can access private fields and set their values. Properties in C# are always public data members. C# properties use get and set methods, also known as accessors to access and assign values to private fields.

Now the question is what are accessors?

The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property, the set accessor specifies that we can assign a value to a private field in a property and without the set accessor property it is like a readonly field. By the get accessor we can access the value of the private field, in other words, it returns a single value. A Get accessor specifies that we can access the value of a field publically.

We have three types of properties: Read/Write, ReadOnly and WriteOnly. Let's see each one by one.

 

Declare and read/write example of property


We create an example that is used for the Name and Age properties for a Person. So first of all, create a Person class then we will use this class in an executable program.

Person.cs
  1. namespace PropertyExample  
  2. {  
  3.     public class Person  
  4.     {  
  5.         private string mName = string.Empty;  
  6.         private int mAge = 0;  
  7.    
  8.         public string Name  
  9.         {  
  10.             get  
  11.             {  
  12.                 return mName;  
  13.             }  
  14.             set  
  15.             {  
  16.                 mName = value;  
  17.             }  
  18.         }  
  19.    
  20.         public int Age  
  21.         {  
  22.             get  
  23.             {  
  24.                 return mAge;  
  25.             }  
  26.             set  
  27.             {  
  28.                 mAge = value;  
  29.             }  
  30.         }  
  31.     }  
  32. }  
Now, we use this class in an executable program by creating an object of the Person class. It is Visual Studio IntelliSense that automatically shows object properties when we enter the dot (. ) operator after an object. In the following figure we can see Age and Name properties of a Person.

1.png

Now we read and write values for the property.

2.png

Finally we get the output of this program:

3.PNG

Let's see the line of code:
  1. objPerson.Name = "Sandeep Singh";  
This line of code is called the set accessor of the Name property in the Person class where we are using the private field mName in the set block, so this line of code actually assigns a value in the mName field, in other words we can assign a value to the private field by property.
  1. Console.WriteLine("Your Name is :{0}", objPerson.Name);  
This line of code is called a get accessor of the Name Property in the Person class; in other words, we can access the mName private field by the Name Property because the Name property get accessor returns a value of the private field mName. So the private field is accessible by the property.

Create Readonly Property


We can also create a read only property. Read only means that we can access the value of a property but we can't assign a value to it. When a property does not have a set accessor then it is a read only property. For example in the person class we have a Gender property that has only a get accessor and doesn't have a set accessor. The Person class is:
  1. public class Person  
  2. {  
  3.     public string Gender  
  4.     {  
  5.         get { return "Male";}  
  6.     }  
  7. }  
When we assign a value to the Gender Property of the Person class object then we get an error that it is a readonly property and can't assign a value to it.

4.png

So the Gender property of the Person class always returns a value and we can't assign a value to it.

Create WriteOnly Property


We can also create a write only property. A write only property is a property that we can assign a value to but can't get that value because that property doesn't have a get accessor. For example we have a Person class that has the property FirstName that has a set accessor but doesn't have a get accessor so it is a write only property.
  1. public class Person  
  2. {  
  3.     private string mFirstName = string.Empty;  
  4.     public string FirstName  
  5.     {  
  6.         set{mFirstName = value;}  
  7.     }  
  8. }  
When we access the value of the FirstName property then we get an error like:

5.png

We can create a write only property when we don't define a get accessor.

Assign Values to Properties on Object Creation


We can also assign values to properties when we are creating an object of the class. For example when we create a Person class object then we can assign a Name and Age property to the person object.

 

  1. Person objPerson = new Person()  
  2. {  
  3.     Name = "Sandeep Singh",  
  4.     Age = 24  
  5. };  
Properties of objects are a block defined by curly braces and in the block each property will be separated by a comma.

Validate Property Value


We can validate a value of a property before it's set to a variable; in other words, we can check a value to be assigned to a private field and if it is correct then it will be assigned to the private field, otherwise it will give an error.

Suppose you are a citizen of India and participate as a voter in a parliament election so your age should be greater than or equal to 18 otherwise you can't vote. To implement this function we have a Voter class and that class has an Age property. The Age property can have a value greater than or equal to 18 otherwise it will show 0 for the age with a message. Our Voter class is:
  1. using System;  
  2. namespace PropertyExample  
  3. {  
  4.     public class Voter  
  5.     {      
  6.         private int mAge = 0;          
  7.         public int Age  
  8.         {  
  9.            get  
  10.             {  
  11.                 return mAge;  
  12.             }  
  13.            set  
  14.             {  
  15.                 if (value >= 18)  
  16.                 {  
  17.                     mAge = value;  
  18.                 }  
  19.                else  
  20.                 {  
  21.                     Console.WriteLine("You are not eligible for voting");         
  22.                 }  
  23.             }  
  24.         }  
  25.     }  
  26. }  
Now create an executable program by which we assign an age value of a Voter.
  1. using System;  
  2. namespace PropertyExample  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Voter objVoter = new Voter();  
  9.             Console.WriteLine("Please enter your age");  
  10.             objVoter.Age = Convert.ToInt32(Console.ReadLine());  
  11.             Console.WriteLine("Your age is :{0} years", objVoter.Age);  
  12.             Console.ReadKey();  
  13.         }  
  14.     }  
  15. }  
Now we enter a value less than 18 and then we get a message with 0 years.

6.PNG

In the output screen above we get a message from the set accessor and the value isn't set in the private field so we get a default value of the private field that we already set to 0. Don't be confused by the message and return value. Here set is not returning a value. It is just printing a message on the console before the get accessor calls the Age property. The following picture shows the message shown before calling the get accessor.

7.png

If we use a value greater than or equal to 18 then we get the private field value without a message.

8.PNG

Use of Property as a method


We can also use a property instead of a method that has one parameter and a return value, because we can define custom logic in the get and set accessors.

Suppose we have a rule for a student that when a student gets marks greater than or equal to 80 then they get 5 bonus marks and when they get marks greater than or equal to 70 but less than or equal to 79 then they get 2 bonus marks. So we define logic in the get accessor that adds marks depending on the student's original marks and thereafter the total marks (original marks + bonus marks) of the student will be returned.

 

  1. using System;  
  2. namespace PropertyExample  
  3. {  
  4.     public class Student  
  5.     {      
  6.         private int mMarks = 0;          
  7.         public int Marks  
  8.         {  
  9.             get  
  10.             {  
  11.                 if(mMarks >= 80)  
  12.                 {  
  13.                     mMarks+=5;  
  14.                 }  
  15.                 else if(mMarks <= 79 && mMarks>=70 )  
  16.                 {  
  17.                     mMarks+=2;                          
  18.                 }                     
  19.                 return mMarks;  
  20.             }  
  21.             set  
  22.             {  
  23.                 mMarks = value;  
  24.             }  
  25.         }  
  26.     }  
  27. }  
Now create a program by which we can input student marks.
  1. using System;  
  2. namespace PropertyExample  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Student objStudent = new Student();  
  9.             Console.WriteLine("Please enter your marks");  
  10.             objStudent.Marks = Convert.ToInt32(Console.ReadLine());  
  11.             Console.WriteLine("Your marks are :{0} marks", objStudent.Marks);  
  12.             Console.ReadKey();  
  13.         }  
  14.     }  
  15. }  
Now we enter more than 80 marks and get the total marks with bonus.

9.PNG 

Auto mapped property

We can also create auto mapped property. When we create auto mapped property then we don't need define to local private field in get and set accessors. For example we have an employee class which has two properties,  one in EmployeeId and another is Name. To define these properties we don't need to create a private field for these two properties and directly declare it.

  1. namespace PropertyExample  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         public int EmployeeId { getset; }  
  6.         public string Name { getset; }  
  7.     }  
  8. }  
Now we access Employee class property in executable program.
  1. using System;  
  2. namespace PropertyExample  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Employee objEmployee = new Employee()  
  9.                                     {  
  10.                                         EmployeeId = 1001,  
  11.                                         Name = "Sandeep"  
  12.                                     };  
  13.             Console.WriteLine("Employee Id is :{0} and Employee Name is :{1}", objEmployee.EmployeeId, objEmployee.Name);  
  14.             Console.ReadKey();  
  15.         }  
  16.     }  
  17. }