Classes, Objects, Properties & Constructors Masterclass
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.
A Class defines fields, properties, and methods that an object instance will contain. Properties wrap private fields safely using get and set accessors.
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());
Static members belong to the class itself rather than any individual instance:
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
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.