Properties In C# With Examples: ReadOnly, WriteOnly Properties in C#

Property in C# is a member of a class that allows classes to read, write, and expose private fields while keeping the implementation details hidden.

In this post, we will try to understand how to use properties in C# with multiple examples.

Properties in CSharp
Properties in C#

Explain properties in C#

C# Properties are special methods that are used to assign and read the value from a private field by using set and get accessors. A get accessor returns a property value, whereas a set accessor assigns a new value.

  • C# Properites don’t have a storage location, unlike fields. Instead, they have accessors to read, write, and compute the values.
  • Properties offer another level of abstraction to expose the private fields as we can’t directly access the private fields outside the class scope.

( get : Retrieve the value  set : Assign the value)                  

C# Properties
Properties in C#

Syntax

The following is the syntax to define a property in C#.

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

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

Properties in C# example

The following example shows how to create a property in C#.

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

 // public property to access the private field
        public string Name
        {
          get {
                return name;
              }

          set {
                name = value;
              }
        }
       // 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 the get block of 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, the private name field is exposed via public property. Here, the get and set accessor of the Name property is used to read and assign the value to the private name field of the Employee class.

The get and set accessor are not only limited to reading or writing the value to the property, but also allow us to perform complex calculations or business logic within the set or get blocks.

Example

Let’s create a property with a get and set accessor.

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

          set {
                name = value;
              }
         }

What are the types of properties in c#?

Following is the list of different types of properties in C#.

C# Properties TypesDescription
01. Read-Write PropertyIt contains both get and set accessor
02. Read-Only PropertyIt contains get accessor only
03. Write-Only PropertyIt contains a set accessor only
04. Auto implemented PropertyIt contains both get and set accessors without having logic inside the block.
Types of properties in C#

C# readonly property

The property that has only the get accessor and no set accessor is called readonly property.
A readonly property allows you to only read the value of a private field. The readonly modifier specifies that the member is not allowed to modify. When you try to set the value of the readonly field/property, a compilation error occurs.

 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 when we try to set the value to the property outside the constructor.

Write Only Properties 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;
        // Write Only Property     
        public string Name
        {
          set {        
                name =value;
              }
        }
C# Write-Only Properties
C# WriteOnly 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.

The properties which do not require any code to be written inside the get method and set method of the class are known as Auto Implemented Properties in C#.

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

In the case of auto-implemented properties, the compiler internally creates private fields that can only be accessed through the property’s getter or setter.

C# Auto Implemented Property

Static Properties in C#

In C#, A property that is created using 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 will only allow you 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
        }
    }
}

C# properties vs fields

In C#, a field is a variable of any type that is declared directly in the class, whereas a property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.

01.  Field : A field is a variable that can be declared directly in a class or struct. A field should nearly always be private members of a class and can be accessed via public get and set properties. Fields are used for data hiding, which is a best practice for Object-Oriented design.

02.  Properties : A property in C# is a member of the class that provides a flexible way to read, write or compute the data of a private field. Properties provide a level of abstraction so that we can change the value of the field while not affecting how they are used by a class.

We can encapsulate the business logic in properties, and adding an extra level of validation in the get and set accessor is acceptable but not always recommended.

Conclusion

This article has provided us with the following insights:

  • Use of the properties and its Syntax.
  • About the write-only and readonly property in C#
  • Use of static property
  • Use of Auto implemented properties in C#

I hope you enjoyed and found this post useful. If you have any questions or comments, please leave them below.

References: MSDN- Properties in C#

Recommanded Articles:

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments