Properties in C#: A Complete Guide

Properties in C#: A Complete Guide

08 Oct 2024
Intermediate
116K Views
25 min read
Learn via Video Course & by Doing Hands-on Labs

Free C# Course Online

Properties in C#

Properties in C# act as a wrapper around a field. C# property is used to assign and read the value from a field by using set and get accessors. The code block for the get accessor is executed when the property is read, and the code block for the set accessor is executed when the property is assigned a new value. A C# property can be created for a public, private, protected, and internal field.

In this C# Tutorial, we will explore more about properties in C#what is an accessor in C#?c# property with real-life examples, different types of properties, when to use properties with examples, the advantage of the property, what is a static property, abstract property, and many more. If you are a beginner in C# programming language, this C# Developer Roadmap article provides you with complete information.

What is Property in C#?

  • C# Properties are used for a class to expose a public way of getting and setting values while hiding implementation or verification code.
  • A get property accessor is used to return the C# property value, and a set property accessor is used to assign a new value.
  • An initial C# property accessor is used to assign a new value only during object construction. These accessors can have different kinds of access levels.
  • Properties in C# can be read-write(get, set), read-only(get), or write-only(set).
  • Write-only properties in C# are used to restrict access to sensitive data.
  • C# Properties do not denote storage locations, and you cannot pass a property as a reference or out parameter.

Example 

Let's elaborate properties in C# Compiler with its example:

 // C# program to illustrate the problems
 // with public and private members
using System;

// public class
public class C1
     { 
     // public data members
       public int rn;
       public string name; 
     // private field
     // private int marks = 35;
     }
 // another public class
  public class C2
         { 
      // Main Method
    public static void Main(string[] args)
    { 
    // Creating object of C1 class
     C1 obj = new C1(); 
    // setting values to public
     // data members of class C1
   obj.rn = 10000;
   obj.name = null;
   // setting values to private
  // data members of class C1
   // obj.mark = 0;
   // display result
     Console.WriteLine("Name: {0} \nRoll No: {1}", obj.name, obj.rn);
          }
    }   

Output

 Name:
Roll No: 10000

Explanation

In the given code, the name variable is not initialized, so its default value is null. The rn variable is set to 10000. The private field marks are commented out and not used, so they do not affect the output.

Using Properties in C#

  • Encapsulation: Properties enable data encapsulation by providing a controlled way to access class fields.
  • Get and Set Methods: Properties in C# have to get and set methods, allowing read and write access to private fields while maintaining data integrity.
  • Syntax: Declare properties using get and set accessors, defining the logic for retrieving and setting values.
  • Access Modifiers: Properties in C# can have access modifiers like public, private, or protected, controlling their visibility.
  • Data Validation: Properties in C# allow validation logic, ensuring only valid data is stored in class fields.
  • Simplified Syntax: Properties simplify the syntax of accessing class members, enhancing code readability and maintainability.

What is Accessor in C#?

In C#, an accessor refers to a method or code block that is used to read or write the value of a private field in a class. Accessors are commonly used in properties to control the access to the underlying data, allowing encapsulation and ensuring data integrity in object-oriented programming.

There are two types of accessors in C# those are:

  • Get Accessor
  • Set Accessor

1. Get Accessor in C#

In C#, a get accessor retrieves the value of a private field in a class. It is part of a property declaration and returns the property value. Get accessors to allow controlled access to class properties, enabling encapsulation and data abstraction in object-oriented programming.

Example

  class Scholar {
          // Declare roll_no field
            private int roll_no;
          // Declare roll_no property
     public int Roll_no 
           { 
       get 
             {
             return roll_no;
             }
          }
        }   

Explanation

The given code defines a class Scholar with a private field roll_no and a public property Roll_no that allows access to the private field. Since the Roll_no property only has a get accessor, you can retrieve the value of the roll_no field but cannot set it from outside the class. There is no output in the code as it does not contain any logic to demonstrate the property usage.

2. Set Accessor in C#

In C#, a set accessor is a method used within a property to assign a value to that property. It allows you to control the behavior when a property's value is set. You define it using the "set" keyword followed by a code block that specifies how the value should be stored or processed.

Example

  class Scholar {
              // Declare roll_no field
                private int roll_no;
             // Declare roll_no property
            public int Roll_no
               { 
                get 
                    {
                       return roll_no;
                     }
              set 
                 {
             roll_no = value;
          }
       }
     }    

Explanation

This C# code defines a class Scholar with a private field roll_no and a public property Roll_no. The property has both get and set accessors, allowing external code to read and modify the private roll_no field. This encapsulation ensures controlled access to the roll_no data within the class.

Accessor Accessibility in C#

  • Accessor modifiers are not permitted on an interface or an explicit interface member implementation.
  • Only when a property possesses both set and get accessors can we employ accessor modifiers.
  • The accessor modifier for an override property has to match the overriding accessor's accessor.
  • The accessor modifier for an override property has to match the overriding accessor's accessor.

Different Types of Property

Properties can be divided into three categories that are read-only, write-only, and read-write properties.

1. Read-Only Property

A read-only property allows you to only retrieve the value of a field. To create a read-only property, you should define the get accessor.

Example

 using System;

class Student
{
    // Private field
    private string _name;

    // Read-only property
    public string Name
    {
        get { return _name; }
    }

    // Constructor to set the read-only property
    public Student(string name)
    {
        _name = name;
    }
}

class Program
{
    static void Main()
    {
        Student student = new Student("Ankita");
        Console.WriteLine("Student Name: " + student.Name);

        // The following line will give an error because the property is read-only:
        // student.Name = "Rahul";  // Uncommenting this will cause a compilation error.
    }
}

Output

 Student Name: Ankita

2. Write-Only Property

A write-only property allows you to only change the value of a field. To create a write-only property, you should define the set accessor.

Example

 using System;

class Employee
{
    // Private field
    private decimal _salary;

    // Write-only property
    public decimal Salary
    {
        set { _salary = value; }
    }

    // Method to display salary (could be restricted in real-world scenarios)
    public void DisplaySalary()
    {
        Console.WriteLine("Salary: " + _salary);
    }
}

class Program
{
    static void Main()
    {
        Employee employee = new Employee();

        // Setting the salary using the write-only property
        employee.Salary = 50000m;

        // Displaying the salary using a method (read access is not allowed directly)
        employee.DisplaySalary();

        // The following line would cause an error because the property is write-only:
        // Console.WriteLine(employee.Salary);  // Uncommenting this will cause a compilation error.
    }
}  

Output

 Salary: 50000

3. Auto-implemented property

  • Auto-implemented properties were introduced with C# 3.0, which makes property declaration more concise.
  • Unlike standard property, in auto-implemented property, a wrapped or backing field is automatically created by the compiler, but it is not available for use by the class's members.
  • public int Name { get; set; }.

Syntax

 public <data_type> PropertyName { get; set; }

Example

 using System;

class Car
{
    // Auto-implemented property for CarName
    public string CarName { get; set; }

    // Auto-implemented property with default value
    public int ModelYear { get; set; } = 2024;
}

class Program
{
    static void Main()
    {
        // Creating an object of Car class
        Car myCar = new Car();

        // Setting value to auto-implemented property
        myCar.CarName = "Honda";

        // Getting value from auto-implemented property
        Console.WriteLine("Car Name: " + myCar.CarName);

        // Getting auto-implemented property with default value
        Console.WriteLine("Model Year: " + myCar.ModelYear);
    }
}  

Output

 Car Name: Honda
Model Year: 2024

4. Static property

You can also declare a property static. To make a static property, you must ensure that the backing store field is also static. Typically, a static property is used to make a singleton class.

 using System;

class Bank
{
    // Static property
    public static decimal InterestRate { get; set; }

    // Instance method to display the interest rate
    public void DisplayInterestRate()
    {
        Console.WriteLine("Current Interest Rate: " + InterestRate + "%");
    }
}

class Program
{
    static void Main()
    {
        // Setting the static property using the class name
        Bank.InterestRate = 4.5m;

        // Creating instances of the Bank class
        Bank bank1 = new Bank();
        Bank bank2 = new Bank();

        // Displaying the static property (same for all instances)
        bank1.DisplayInterestRate();
        bank2.DisplayInterestRate();

        // Updating the static property
        Bank.InterestRate = 5.0m;

        // Displaying the updated interest rate
        bank1.DisplayInterestRate();
        bank2.DisplayInterestRate();
    }
}   

Output

 Current Interest Rate: 4.5%
Current Interest Rate: 4.5%
Current Interest Rate: 5.0%
Current Interest Rate: 5.0%

5. Abstract property

An abstract property declaration does not provide an implementation of the property accessors. It leaves the implementation of the accessor to derived classes. Abstract properties are declared within an abstract class or interface.

Example

 using System;

abstract class Shape
{
    // Abstract property for calculating the area
    public abstract double Area { get; }

    // Abstract property for calculating the perimeter
    public abstract double Perimeter { get; }
}

class Circle : Shape
{
    private double radius;

    // Constructor to initialize the radius
    public Circle(double radius)
    {
        this.radius = radius;
    }

    // Implementing the abstract Area property
    public override double Area
    {
        get { return Math.PI * radius * radius; }
    }

    // Implementing the abstract Perimeter property
    public override double Perimeter
    {
        get { return 2 * Math.PI * radius; }
    }
}

class Program
{
    static void Main()
    {
        // Creating a Circle object
        Circle circle = new Circle(5);

        // Accessing the implemented properties
        Console.WriteLine("Circle Area: " + circle.Area);
        Console.WriteLine("Circle Perimeter: " + circle.Perimeter);
    }
}  

Output

 Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793

Some Other Examples of C# Properties

1. C# Feature with Polymorphism

In C#, polymorphism allows derived classes to provide specific implementations for properties or methods that are defined in a base class. Using properties, you can implement runtime polymorphism with the help of virtual, override, and abstract keywords.

Example

 using System;

class Animal
{
    // Virtual property allows overriding in derived classes
    public virtual string Sound { get; set; }

    // Method to describe the sound
    public void MakeSound()
    {
        Console.WriteLine("Animal makes sound: " + Sound);
    }
}

class Dog : Animal
{
    // Overriding the Sound property
    public override string Sound
    {
        get { return "Bark"; }
    }
}

class Cat : Animal
{
    // Overriding the Sound property
    public override string Sound
    {
        get { return "Meow"; }
    }
}

class Program
{
    static void Main()
    {
        // Polymorphism using base class reference and derived class objects
        Animal myAnimal;

        myAnimal = new Dog();
        myAnimal.MakeSound();  // Output: Animal makes sound: Bark

        myAnimal = new Cat();
        myAnimal.MakeSound();  // Output: Animal makes sound: Meow
    }
}  

Output

 Animal makes sound: Bark
Animal makes sound: Meow

2. C# Feature with Inheritance

In C#, inheritance is one of the key features of Object-Oriented Programming (OOP) that allows a class to inherit members (fields, methods, properties, etc.) from another class. This promotes code reuse, helps organize and structure programs, and allows for the implementation of polymorphism.

Example

 using System;

class Vehicle  // Base class
{
    public string Brand { get; set; }

    // Method in the base class
    public void StartEngine()
    {
        Console.WriteLine(Brand + " engine started.");
    }
}

// Derived class inheriting from Vehicle
class Car : Vehicle
{
    public string Model { get; set; }

    // Method in the derived class
    public void DisplayInfo()
    {
        Console.WriteLine("Brand: " + Brand + ", Model: " + Model);
    }
}

class Program
{
    static void Main()
    {
        // Creating an instance of the derived class
        Car myCar = new Car();

        // Accessing base class members from the derived class
        myCar.Brand = "Honda";  // Inherited from Vehicle
        myCar.Model = "Civic";  // Specific to Car

        // Calling methods
        myCar.StartEngine();    // Inherited method from Vehicle
        myCar.DisplayInfo();    // Method in Car class
    }
}   

Output

 Honda engine started.
Brand: Honda, Model: Civic

When to use Properties in C#

  • Need to validate data before assigning it to a field.
  • Data needs to be immediately computed before assigning or retrieving it to a field.
  • Need to log all access for a field. Need to protect a field by reading and writing.

Advantages of properties in C#

  1. It provides better control of class members and avoids the complexity of the code.
  2. It ensures the security of the data fields.
  3. It also validates the data before storing it in the data fields.
  4. Fields are made read-only or write-only using the properties.
  5. Properties also make the program flexible, which means the programmer can change one part of the code without affecting other parts.
Read More:
OOPs Interview Questions and Answers in C#
Top 50 C# Interview Questions and Answers To Get Hired
    Conclusion

    In conclusion, we can see that C# properties play a crucial role in encapsulating data, providing a structured way to manage access to class fields while enhancing code readability and maintainability. Their flexibility in implementation, along with support for inheritance and polymorphism, makes them an essential feature of object-oriented programming in C#. For mastering in C#, Scholarhat provides a Full-Stack .NET Developer Certification Training Course.

    FAQs

    Q1. What is field and property in C#?

    In C#, a field is a variable (that can be of any type) that is defined inside a class. It can be used to define the characteristics of an object or a class. On the other hand, a property is a member of the class that provides an abstraction to set (write) and get (read) the value of a private field.

    Q2. What is the purpose of read-only and write-only properties?

    Read-only properties allow you to retrieve values but not set them outside the class, while write-only properties allow you to set values but not retrieve them. These properties are useful for encapsulating data and controlling access.

    Q3. Can properties have different access modifiers?

    Yes, properties can have different access modifiers (public, private, protected, etc.) for their get and set accessors, allowing fine-grained control over how they can be accessed and modified.

    Q4. What is the difference between a virtual property and an abstract property?

     A virtual property provides a default implementation that can be overridden in derived classes, whereas an abstract property does not provide an implementation and must be overridden in derived classes. 

    Take our Csharp skill challenge to evaluate yourself!

    In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

    GET FREE CHALLENGE

    Share Article

    Live Classes Schedule

    Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
    .NET Solution Architect Certification TrainingOct 26SAT, SUN
    Filling Fast
    05:30PM to 07:30PM (IST)
    Get Details
    .NET Microservices Certification TrainingOct 26SAT, SUN
    Filling Fast
    05:30PM to 07:30PM (IST)
    Get Details
    ASP.NET Core Certification TrainingOct 26SAT, SUN
    Filling Fast
    09:30AM to 11:30AM (IST)
    Get Details
    Advanced Full-Stack .NET Developer Certification TrainingOct 26SAT, SUN
    Filling Fast
    09:30AM to 11:30AM (IST)
    Get Details
    Azure Developer Certification TrainingOct 27SAT, SUN
    Filling Fast
    08:30PM to 10:30PM (IST)
    Get Details
    Microsoft Azure Cloud Architect with AINov 10SAT, SUN
    Filling Fast
    07:00AM to 09:00AM (IST)
    Get Details

    Can't find convenient schedule? Let us know

    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

    Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
    Accept cookies & close this