</>
Skip to content
C# lessons (21/34)

C# — Properties

Auto-properties

using System;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; } = "unknown";
}

class Program
{
    static void Main()
    {
        var p = new Person { Name = "Alice", Age = 30 };
        Console.WriteLine($"{p.Name}, {p.Age}");
    }
}

Read-only properties

using System;

public class Circle
{
    public double Radius { get; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    // Computed read-only property
    public double Area => Math.PI * Radius * Radius;
    public double Circumference => 2 * Math.PI * Radius;
}

class Program
{
    static void Main()
    {
        var c = new Circle(5);
        Console.WriteLine($"Area: {c.Area:F2}");           // 78.54
        Console.WriteLine($"Circumference: {c.Circumference:F2}"); // 31.42
        // c.Radius = 10; // Error: get-only
    }
}

Properties with validation

using System;

public class Person
{
    private string name = "";
    private int age;

    public string Name
    {
        get => name;
        set
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentException("Name cannot be empty");
            name = value.Trim();
        }
    }

    public int Age
    {
        get => age;
        set
        {
            if (value < 0 || value > 150)
                throw new ArgumentOutOfRangeException(nameof(value));
            age = value;
        }
    }
}

class Program
{
    static void Main()
    {
        var p = new Person { Name = "Alice", Age = 30 };
        Console.WriteLine($"{p.Name}, {p.Age}");

        try
        {
            p.Age = -5;
        }
        catch (ArgumentOutOfRangeException e)
        {
            Console.WriteLine($"Error: {e.Message}");
        }
    }
}

Init-only setters (C# 9)

using System;

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

class Program
{
    static void Main()
    {
        var p = new Person { Name = "Alice", Age = 30 };
        Console.WriteLine($"{p.Name}, {p.Age}");

        // p.Name = "Bob"; // Error: init-only
    }
}

Expression-bodied properties

using System;

public class Point
{
    public double X { get; set; }
    public double Y { get; set; }

    // Expression-bodied read-only
    public double DistanceFromOrigin => Math.Sqrt(X * X + Y * Y);

    // Override ToString
    public override string ToString() => $"({X}, {Y})";
}

class Program
{
    static void Main()
    {
        var p = new Point { X = 3, Y = 4 };
        Console.WriteLine(p);                    // (3, 4)
        Console.WriteLine($"Distance: {p.DistanceFromOrigin}"); // 5
    }
}

Indexers

using System;

public class TemperatureLog
{
    private double[] temps = new double[24];

    public double this[int hour]
    {
        get => temps[hour];
        set => temps[hour] = value;
    }
}

class Program
{
    static void Main()
    {
        var log = new TemperatureLog();
        log[8] = 22.5;
        log[14] = 28.0;

        Console.WriteLine($"8 AM: {log[8]}°C");
        Console.WriteLine($"2 PM: {log[14]}°C");
    }
}

Property patterns (C# 8+)

using System;

record Person(string Name, int Age, string City);

string Classify(Person p) => p switch
{
    { Age: < 13 } => "Child",
    { Age: < 18 } => "Teenager",
    { City: "NYC" } => "New Yorker",
    _ => "Adult"
};

class Program
{
    static void Main()
    {
        var alice = new Person("Alice", 30, "NYC");
        var bob = new Person("Bob", 10, "LA");

        Console.WriteLine(Classify(alice)); // New Yorker
        Console.WriteLine(Classify(bob));   // Child
    }
}

Destructuring

using System;

record Point(double X, double Y);

class Program
{
    static void Main()
    {
        var p = new Point(3, 4);

        // Positional deconstruction
        var (x, y) = p;
        Console.WriteLine($"X: {x}, Y: {y}");

        // discard
        var (_, yOnly) = p;
        Console.WriteLine($"Y: {yOnly}");
    }
}

Mini Practice

Write C# code that:

  1. Creates a class with a validated property
  2. Uses init-only setters
  3. Implements an indexer for a collection
  4. Uses property patterns in a switch expression

Up Next

In the next lesson, you'll learn about Inheritance — deriving classes and code reuse.

Related Topics

Frequently Asked Questions about Properties

What is Properties in C#?

Properties is a fundamental concept in C#. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Properties?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Properties.

Why is Properties important in C#?

Properties is essential for C# development. Understanding this concept will help you write better code and solve real-world problems more effectively.