Labs ICT
Pro Login

Properties

In the last lesson, you saw how to create classes with public fields. But there is a better way to expose data in C# — properties. They look like fields but behave like methods. Sounds weird? Let me show you.

What Are Properties?

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Person p = new Person();
p.Name = "Amina";  // This calls the setter
Console.WriteLine(p.Name);  // This calls the getter

At first glance, this looks exactly like using public fields. But behind the scenes, properties are actually methods that control how values are accessed and modified. The get keyword defines the getter (what happens when you read the value), and set defines the setter (what happens when you assign a value).

Why Not Just Use Public Fields?

Because properties give you control. You can add validation, computed values, or notification logic:

class Student
{
    private int age;

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

Student s = new Student();
s.Age = 25;     // Works fine
s.Age = -5;     // Invalid age!
Console.WriteLine(s.Age);  // 0 (not changed)

With a public field, you could set Age = -5 and nobody would stop you. With a property, you can validate the input and reject invalid values.

Auto-Implemented Properties

When you do not need any special logic, you can use the short syntax:

// This is the same as writing a full property with a private field
public string Name { get; set; }
public int Score { get; set; }

// You can also make it read-only (only getter)
public string Id { get; }

// Or initialize with a default value
public bool IsActive { get; set; } = true;

Computed Properties

Sometimes a property does not store data — it calculates it from other properties:

class Rectangle
{
    public double Length { get; set; }
    public double Width { get; set; }

    // Computed property — no backing field
    public double Area
    {
        get { return Length * Width; }
    }

    public double Perimeter
    {
        get { return 2 * (Length + Width); }
    }
}

Rectangle rect = new Rectangle();
rect.Length = 5;
rect.Width = 3;
Console.WriteLine($"Area: {rect.Area}");         // Area: 15
Console.WriteLine($"Perimeter: {rect.Perimeter}");  // Perimeter: 16

The Area property does not store anything. It computes the value on the fly whenever you access it. If Length or Width changes, Area automatically reflects the new value.