← Back to Tutorials Chapter 5

OOP Concepts

Classes & Objects

A class is a blueprint for creating objects. An object is an instance of a class.

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

    public Person(string name, int age) {
        Name = name;
        Age = age;
    }

    public void Introduce() {
        Console.WriteLine($"Hi, I'm {Name} and I'm {Age}.");
    }
}

// Creating objects
Person p = new Person("Alice", 30);
p.Introduce();

Access Modifiers

Properties

class Product {
    private decimal price;
    public decimal Price {
        get { return price; }
        set { if (value > 0) price = value; }
    }

    // Auto-property
    public string Name { get; set; }

    // Read-only property
    public decimal Tax => Price * 0.08m;
}

Static Members

class MathHelper {
    public static double PI = 3.14159;
    public static int Add(int a, int b) => a + b;
}
Console.WriteLine(MathHelper.PI);
C# class diagram

Practice Task

Write a C# program that applies the concepts covered in this chapter. Experiment with different inputs and test your understanding.