Properties In C# with examples

In this post, we’ll look at how to use properties in C# with some examples.

Properties in CSharp
Properties in C#

What are the Properties in C#?

In C#, a property is an extension of a field that allows classes to read, write, and disclose private fields while keeping the implementation details hidden.

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. In simple words, Property in C# is used to get and set the data from the private field in a class.

( get : Retrieve  set : Assign)                  

C# Properties
Properties in C#

Property Syntax in C#

The following are examples 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 Properties in C#

Let’s take a look at the following example of defining 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;
              }
        }

        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 reading or writing the value to the property but also allow us to do very complicated calculations or business logic inside the set or get blocks.

Following is the example of 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;
              }
         }

ReadOnly Properties in C#

The property that has only the get accessor and not the set accessor is known as the 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

        }

    }
}

What are the types of properties in C#?

Let’s take a look at the following table having different types of properties.

C# Properties TypesDescription
1. Read-Write PropertyWhen a property contains both get and set accessor
2. Read-Only PropertyWhen a property contains get accessor only
3. Write-Only PropertyWhen a property contains a set accessor only
4. Auto implemented PropertyThe property contains both get and set accessors without having logic inside the block.
Types of properties in C#

C# properties vs fields

1.  Field : A field is a variable that can be declared directly in a class or struct. Fields in C# should nearly always be private members of a class and can be accessed via public get and set properties. Fields can be constants if required. Fields are used for data hiding, which is a best practice for Object-Oriented Design. We can perform any internal operations on a field, so long as it is private and we can expose its value with public property.

2.  Properties : A property in C# is a member of the class that provides a flexible mechanism 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 additional level of validation in the get and set method is fine, but not always encouraged.

Conclusion:

The following are some of the insights we’ve gained from this article:

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

I hope you enjoyed this post and found it useful. In case you have any doubt, please post your feedback, question, or comments.

Articles to Check Out

Leave a Comment