Labs ICT
โญ Pro Login

Classes and Objects

Object-oriented programming (OOP) is a way of organizing your code around objects instead of functions. It is the backbone of C# and .NET. Once you understand OOP, you will see it everywhere โ€” in every library, framework, and application you use.

What Is a Class?

A class is a blueprint. It defines what data an object will hold and what actions it can perform. Think of it like an architectural plan for a house โ€” the plan itself is not a house, but you can use it to build many houses.

class Student
{
    public string Name;
    public int Age;
    public double GPA;

    public void Introduce()
    {
        Console.WriteLine($"Hi, I am {Name}, {Age} years old.");
    }
}

This Student class has three fields (Name, Age, GPA) and one method (Introduce). The public keyword means these members can be accessed from outside the class.

Creating Objects

An object is an instance of a class. You create one using the new keyword:

Student student1 = new Student();
student1.Name = "Amina";
student1.Age = 22;
student1.GPA = 3.8;

Student student2 = new Student();
student2.Name = "Bilal";
student2.Age = 25;
student2.GPA = 3.5;

student1.Introduce();  // Hi, I am Amina, 22 years old.
student2.Introduce();  // Hi, I am Bilal, 25 years old.

Both students have the same structure (same fields and methods), but they hold different data. That is the beauty of classes and objects โ€” one blueprint, many instances.

Constructors

A constructor is a special method that runs when you create an object. It is perfect for setting up initial values:

class Student
{
    public string Name;
    public int Age;

    // Constructor
    public Student(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void Introduce()
    {
        Console.WriteLine($"Hi, I am {Name}, {Age} years old.");
    }
}

// Creating objects with the constructor
Student s1 = new Student("Fatima", 21);
Student s2 = new Student("Musa", 23);

s1.Introduce();  // Hi, I am Fatima, 21 years old.
s2.Introduce();  // Hi, I am Musa, 23 years old.

Constructors have the same name as the class and no return type. They make your code cleaner because you set up the object in one line instead of assigning each field separately.

Why Does This Matter?

OOP helps you organize complex programs. Instead of having hundreds of variables and functions floating around, you group related data and behavior into classes. This makes your code easier to understand, maintain, and reuse.

๐Ÿงช Quick Quiz

What is a class in C#?