C# Properties

Properties and Encapsulation

Before going on properties let’s have a look at why the concept of properties came into C#. This is because of two reasons: If the members of a class are private then how another class in C# will be able to read, write, or compute the value of that field?

If the members of the class are public then another class may misuse that member.

Properties in C# are members of a class, just like methods, fields, and events. They fall under the category of class members or object-oriented programming (OOP) concepts. Specifically, properties are a part of the encapsulation principle in OOP

Using a private variable with a public property instead of directly using a public variable has advantage:

Encapsulation and Data Hiding

By keeping the field private and using public property, you control how the data is accessed and modified. This is a key principle of encapsulation in object-oriented programming. It hides the internal implementation details and only exposes the necessary interface.

Example: Student Class with a Name Property

In this example, we’ll have a student class with a private field for the student’s name and a public property to access and modify that name.

using System;
public class Student
{
    // Private field
    private string name;
    // Public property
    public string Name
    {
        get { return name; }  // Getter: retrieves the value
        set { name = value; }  // Setter: sets the value
    }
}
public class Program
{
    public static void Main()
    {
        // Create a new Student object
        Student student = new Student();
        // Use the property to set the name
        student.Name = “John”;
        // Use the property to get the name
        Console.WriteLine(student.Name);  // Output: John
    }
}

Course Video :

Course Video English :
Task:

1. Basic Property:
Create a class Rectangle with properties Length and Width. Add a method to calculate and return the area of the rectangle. Create an object of Rectangle in the Main method, set the properties, and print the area.

2. Read-Only Property:
Create a class Circle with a read-only property Radius and a method to calculate and return the circumference. Create an object of Circle in the Main method, set the radius through the constructor, and print the circumference.

3. Auto-Implemented Property:
Create a class Student with auto-implemented properties Name, Age, and Grade. Create an object of Student in the Main method, set the properties, and print them.

4. Property with Validation:
Create a class Employee with properties Name, Age, and Salary. Ensure that the Age property can only be set if the value is between 18 and 65. Create an object of Employee in the Main method, set the properties, and print them.

5. Static Property:
Create a class Counter with a static property Count that tracks the number of instances created. Increment the Count property in the constructor. Create multiple objects of Counter in the Main method and print the value of Count.

6. Calculated Property:
Create a class Temperature with a property Celsius and a read-only property Fahrenheit that returns the temperature in Fahrenheit. Create an object of Temperature in the Main method, set the Celsius property, and print both Celsius and Fahrenheit.

7. Private Set Property:
Create a class BankAccount with properties AccountNumber, Balance, and AccountHolder. The Balance property should have a private set accessor. Add methods to deposit and withdraw money. Create an object of BankAccount in the Main method, perform some transactions, and print the balance.

8. Property with Default Value:
Create a class Product with properties Name, Price, and Stock. The Stock property should have a default value of 100. Create an object of Product in the Main method, set the properties, and print them.

Frequently Asked Questions

Still have a question?

Let's talk

Properties in C# are special methods called accessors. They provide a flexible mechanism to read, write, or compute the values of private fields, encapsulating data and ensuring validation when needed.

Fields are variables directly declared in a class, while properties use getter and setter methods to encapsulate field values, allowing validation and additional logic when accessing data.

The main types include:

    • Auto-Implemented Properties: Simplified syntax without requiring explicit backing fields.
    • Read-Only Properties: Only have a getter accessor.
    • Write-Only Properties: Only have a setter accessor.
    • Computed Properties: Have logic within their get or set accessors.

Auto-implemented properties allow you to declare properties without explicitly defining a backing field. The compiler automatically generates the backing field.

Yes, both getter and setter accessors can include custom logic for validation, computation, or other operations before returning or assigning a value.

  • Getter: Used to retrieve the value of a property.
  • Setter: Used to assign a value to the property.

A read-only property includes only a getter, while a write-only property includes only a setter.

By marking the setter as private, you restrict write access to the property within the class while allowing read access publicly. Example: public string Name { get; private set; }

Computed properties dynamically calculate their values based on other properties or fields in the class. They do not store any data but provide the computed result on access.

Yes, properties can be overridden using the virtual keyword in the base class and the override keyword in the derived class.

Iqra Technology Academy provides free video tutorials in Hindi that explain properties in C# with practical examples. Our tutorials cover the concept from basics to advanced, including hands-on examples.

At Iqra Technology Academy, we offer a free online course in Hindi that covers properties in C#. The course is designed for beginners and includes practical examples to help you master the concept of properties in C#.

Properties in C# allow for better data encapsulation, providing a clean interface to access private fields. They also enable validation, change tracking, and encapsulation of logic for reading or writing values.