Classes, Objects, Properties & Constructors Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 15 of 35 ๐Ÿ“‚ Phase 6: Methods & OOP ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Classes & Objects ยท Fields vs Properties ยท Auto-Properties ({ get; set; }) ยท Constructors ยท Object Initializer ยท this Keyword ยท Static Members ยท ToString()

Welcome to Phase 6 (Chapter 15): C# Classes, Objects, Properties & Constructors Masterclass! Object-Oriented Programming (OOP) organizes software into Classes (blueprints) and Objects (runtime instances). In this lesson, we explore fields, automatic properties ({ get; set; }), default and parameterized constructors, object initializers, this keyword, static members, nested classes, and ToString() overriding.

1Class Definition, Properties & Constructors

A Class defines fields, properties, and methods that an object instance will contain. Properties wrap private fields safely using get and set accessors.

C# โ€” Student Class Definition โ–ถ Run in Compiler
class Student
{
    // Auto-Properties
    public string Name { get; set; } = "";
    public int Age { get; set; }

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

    public void DisplayDetails()
    {
        Console.WriteLine($"Student: {Name} - Age: {Age}");
    }

    public override string ToString() => $"Student({Name}, {Age})";
}

Student student = new("Ravi", 20);
student.DisplayDetails();
Console.WriteLine(student.ToString());
2Static Members & Static Classes

Static members belong to the class itself rather than any individual instance:

C# โ€” Static Members โ–ถ Run in Compiler
class Counter
{
    public static int Count = 0; // Shared across ALL instances

    public Counter()
    {
        Count++;
    }
}

Counter c1 = new Counter();
Counter c2 = new Counter();
Console.WriteLine($"Total Objects Created: {Counter.Count}"); // 2
3Technical FAQs

Q1: What is the difference between a Field and a Property?

A Field is a raw private data variable. A Property wraps a field with get and set accessors to provide encapsulation, data validation, and controlled read/write access.

Q2: What is the 'this' keyword?

this refers to the current instance of the class, helping distinguish between constructor parameters and class fields with the same name.