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

C# Constructors

A constructor is a special method called automatically when an object is created. C# supports multiple constructors through overloading.

1 - Default Constructor

public class Point
{
    public double X { get; set; }
    public double Y { get; set; }

    // Default constructor — no parameters
    public Point()
    {
        X = 0;
        Y = 0;
    }
}

var origin = new Point();
Console.WriteLine($"{origin.X}, {origin.Y}"); // 0, 0

2 - Parameterised Constructor

public class Point
{
    public double X { get; }
    public double Y { get; }

    public Point(double x, double y)
    {
        X = x;
        Y = y;
    }

    public double DistanceTo(Point other) =>
        Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));
}

var a = new Point(0, 0);
var b = new Point(3, 4);
Console.WriteLine(a.DistanceTo(b)); // 5

3 - Constructor Chaining (this)

public class Rectangle
{
    public double Width  { get; }
    public double Height { get; }

    // Delegates to the two-parameter constructor
    public Rectangle(double side) : this(side, side) { }

    public Rectangle(double width, double height)
    {
        Width  = width;
        Height = height;
    }
}

4 - Primary Constructors (C# 12)

public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int    Age  { get; } = age;
    public string Greet() => $"Hi, I'm {name}!";
}

var p = new Person("Alice", 30);
Console.WriteLine(p.Greet()); // Hi, I'm Alice!

Note: If you do not define any constructor, C# provides a free parameterless constructor that zero-initialises all fields. As soon as you define any constructor, that free one disappears.

-Tip-