Properties In C# with examples

In this article, we are going to talk about the use of properties in C# with examples.

What are the Properties in C#

A Property in C# is an extension of a field that provides a public way for the classes to read, write, and expose the private fields while hiding the implementation details.

Properties in C# are actually a special kind of getter and setter methods wrapped around a private variable. A  get  property accessor is used to retrieve the value and the  set  accessor is used to assign the new value.

( get : Retrieve  set : Assign)                  

C# Properties
Properties in C#

Property Syntax in C#

The following are the example of defining a property in C#.

<Access Modifier> <Return Type> <Property Name>
  {
   get { 
         // get accessor
         // return value
       }

    set {
	      // set accessor
          // assign a new value
         }
  }

We can see in the above example, The get accessor block executes the statements when we read the value from a property.
Similarly, the set block gets executed when we assign the value to the property.

Example of Property in C#

using System;
namespace PropertyDemo
{
    class Employee
    {
        private string name;

        public string Name
        {
          get {
                return name;
              }

          set {
                name = value;
              }
        }

        public Employee(string name)
        {
            this.name = name;
        }

    }
    public class Programs
    {
           
        public static void Main(string[] args)
        {
            Employee employee = new Employee("Shekh Ali"); // Constructor
            string name = employee.Name; // Calling get block of the Name property
            Console.WriteLine($"Name : {name}");

            employee.Name = "Mark Adams"; // Calling set block to assign the new value.
            Console.WriteLine($"Name : {employee.Name}");

            Console.ReadLine();         
        }
    }
}

In the above example, we can see that the private field  name  is now exposed through public property. If we want to read the value of the  name  field we have to call the Name property with the  employee  object. Similarly, if we want to set a new value to the  name  field, we have to call the set block of the Name property.

The get accessor and set accessor are not only limited to read or write the value to the property but also it allows us to do very complicated calculations or business logic inside the set or get blocks.

Following is the example.

public string Name
        {
          get {
                if (string.IsNullOrEmpty(name))
                { 
                    // Business Logic
                    name = "Name is not available !";
                }
                return name;
               }

          set {
                name = value;
              }
         }

ReadOnly Properties in C#

The property that has only the get accessor and not the set accessor is known as Read-Only property.
A Read-Only property allows us to only read the value of the private field.
The moment we try to set the value, the compiler will throw an error message.

 class Employee
    {
        private string name;

        // ReadOnly Property     
        public string Name
        {
          get {        
                return name;
              }
        }
        // Constructor
        public Employee(string name)
        {
            this.name = name;
        }
    }
    public class Programs
    {
           
        public static void Main(string[] args)
        {
            Employee employee = new Employee("Shekh Ali"); // Constructor
            string name = employee.Name; // Calling get block of the ReadOnly property

            Console.WriteLine($"Name : {name}");
            employee.Name = "Mark Adams"; // Calling set block to assign the new value.
            Console.WriteLine($"Name : {employee.Name}");

            Console.ReadLine();         
        }

    }
C# Read-Only Property
C# ReadOnly Property

As we can see in the above example, It throws an error the moment we try to set the value to the property outside the constructor.

Write Only Properties in C#

Similarly, as we have created a read-only property, we can also create a write-only property in C#.
The Write-Only property has only the set block and not the get block. It allows us to only set the values and not to read the value.
If we try to read the value, It will throw an error message.

        private string name;
        // WriteOnly Property     
        public string Name
        {
          set {        
                name =value;
              }
        }
C# Write-Only Properties
C# Write-Only Property in C#

Auto Implemented Properties in C#

In C#, An auto-implemented property contains both the get accessor and set accessor without having any business logic.
It makes code more clean and readable and used when no additional business logic or calculation is needed in the get or set block.

 // Auto Implemented Property  
   
    public string Name { get; set; }

The compiler internally creates the private fields in case of auto-implemented property which can only be accessed through the getter or setter of the property.

C# Auto Implemented Property

Static Properties in C#

In C#, A property marked with the static keyword is known as a static property.
A static property can access directly by the class name without creating an instance of that class because the static property belongs to the class rather than the object of the class.
A static property in C# can only allow us to use the static variables inside the getter and setter block.

using System;
namespace PropertyDemo
{
   public class Employee
    {
        // Static field
        private static string name;
        // Static Property     
        public static string Name
        {
            get
            {
                return name;
            }

            set
            {
                name = value;
            }
        }      
    }
    public class Programs
    {         
        public static void Main(string[] args)
        { 
            // Accessing static property by the class name.
            Employee.Name = "Shekh Ali"; // Set Value
            Console.WriteLine($"Name : {Employee.Name}"); // Get Value

        }

    }
}

Property Types Property Description
Read-Write When a property contains both get and set accessor
Read-Only When a property contain get accessor only
Write-Only When a property contain set accessor only
Auto implemented Contains both get and set accessor without having logic inside the block.

Conclusion:

In this article, the following are the things which we have learned:

    • Use of the properties and it’s Syntax.
    • About the Read-Only and the Write only property
    • Use of Static property
    • Use of Auto implemented properties¬†

I hope you enjoyed this post and found it useful. Thanks for visiting.

Leave a Reply

Your email address will not be published. Required fields are marked *

two × three =