C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Classes and Objects

C# Classes and Objects

A class is a blueprint for creating objects. An object is an instance of a class that holds its own data and exposes behaviour.

1 - Defining a Class

public class Car
{
    // Fields
    private string _brand;
    private int    _year;

    // Constructor
    public Car(string brand, int year)
    {
        _brand = brand;
        _year  = year;
    }

    // Method
    public string Describe() => $"{_year} {_brand}";
}

// Creating objects
var car1 = new Car("Toyota", 2024);
var car2 = new Car("Tesla",  2023);

Console.WriteLine(car1.Describe()); // 2024 Toyota
Console.WriteLine(car2.Describe()); // 2023 Tesla

2 - Object Initializer Syntax

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

var person = new Person { Name = "Alice", Age = 30 };
Console.WriteLine(person.Name); // Alice

3 - The this Keyword

public class Circle
{
    private double _radius;

    public Circle(double radius)
    {
        this._radius = radius; // disambiguates field vs parameter
    }

    public Circle Scale(double factor) =>
        new Circle(this._radius * factor); // return new instance
}

Note: In C#, classes are reference types — multiple variables can reference the same object. Use struct when you need value semantics (copied on assignment), like coordinates or color values.

-Tip-