Lesson 13 — Properties in C# (Auto, Custom, Get/Set, Backing Fields)

Properties are one of the most important features of C# and are closely linked to encapsulation, one of the pillars of OOP.

In simple words:

A property is a smart way to access private fields with controlled logic.

Properties help protect data while making code clean, readable, and easy to maintain.


🌟 What is a Property in C#?

A property is a member of a class that provides:

  • Controlled access to private fields
  • A way to read and write values
  • Optional validation logic

It looks like a field but behaves like a method.


🔒 Why Use Properties?

✔ To protect fields using encapsulation
✔ To validate data before setting it
✔ To provide read-only or write-only access
✔ To simplify syntax using get/set
✔ To avoid exposing private variables directly


🧱 1️⃣ Auto-Implemented Properties (Auto Properties)

The simplest type of property.

public class Student
{
    public string Name { get; set; }
}

C# automatically creates a hidden private field.

Usage:

Student s = new Student();
s.Name = "Amit";
Console.WriteLine(s.Name);

✔ Short
✔ Clean
✔ No need to manually create a field


🧱 2️⃣ Custom Properties (With Backing Field)

Used when you need validation or custom logic.

public class Student
{
    private int age;    // backing field

    public int Age
    {
        get { return age; }
        set
        {
            if (value > 0 && value < 120)
                age = value;
            else
                Console.WriteLine("Invalid age!");
        }
    }
}

Usage:

Student s = new Student();
s.Age = 20;   // valid
s.Age = -5;   // Invalid age!


🧱 3️⃣ Read-Only Property

A property that can only be read (no setter).

public class Product
{
    public string Id { get; } = Guid.NewGuid().ToString();
}

✔ Useful for IDs, timestamps, etc.


🧱 4️⃣ Write-Only Property

Rarely used.

public class PasswordManager
{
    private string password;

    public string Password
    {
        set { password = value; }
    }
}

No one can read the password from outside.


🧱 5️⃣ Expression-Bodied Properties

Cleaner syntax introduced in modern C#.

public class Circle
{
    public double Radius { get; set; }

    public double Area => 3.14 * Radius * Radius;
}

Read-only property with short syntax.


🧱 6️⃣ Init-Only Properties (C# 9+)

Allows values to be set only during object creation.

public class User
{
    public string Username { get; init; }
}

Usage:

var u = new User { Username = "admin" };

After creation, it cannot be changed.


✨ Full Practical Example — Employee Class with Properties

public class Employee
{
    private double salary;

    public string Name { get; set; }        // auto property

    public double Salary                    // custom property
    {
        get { return salary; }
        set
        {
            if (value >= 10000)
                salary = value;
            else
                Console.WriteLine("Salary must be at least 10000.");
        }
    }

    public string EmployeeCode { get; } = Guid.NewGuid().ToString();  // read-only property
}

Usage:

Employee e = new Employee();
e.Name = "Riya";
e.Salary = 9000;   // invalid
e.Salary = 20000;  // valid


🧠 Property vs Field (Easy Comparison)

FieldProperty
Variable inside a classSmart wrapper over field
No validationSupports validation
Always direct accessCan restrict access
Not safe to exposeSafe to expose
Used internallyUsed for external access

🌈 Real-World Analogy

✔ Field → Bank Locker Inside Branch

You cannot open it directly.

✔ Property → The Bank Employee

You request them, and they check rules before allowing access.

This is encapsulation.


📝 Mini Exercise

Create a class Book with:

  • Auto property → Title
  • Backing field + property → Price (cannot be negative)
  • Read-only property → ISBN (generated automatically)

Create two books and print their details.


🔍 FAQs

Q1: Why not expose fields directly?

It breaks encapsulation and allows invalid data.

Q2: Can properties have both private get and public set?

Yes.

Example:

public int Age { private get; set; }

Q3: Can properties be virtual?

Yes, they can be overridden in derived classes.

Q4: Are auto-properties faster?

Yes, and they make code simpler.


🎉 Conclusion

You now understand:

✔ What properties are
✔ Why they are used
✔ Auto-properties
✔ Custom properties with backing fields
✔ Read-only and write-only properties
✔ Expression-bodied and init-only properties

Properties are the standard way to implement encapsulation in modern C#.