SyntaxStudy
Sign Up
C# Classes, Properties, and Constructors
C# Beginner 1 min read

Classes, Properties, and Constructors

A class is the primary building block of object-oriented C# programs. It encapsulates data (fields) and behaviour (methods) into a single unit. Properties are preferred over public fields because they expose a controlled interface — get/set accessors — while hiding the underlying storage. Auto-implemented properties let the compiler generate backing storage automatically. C# 9 init-only properties (`init` accessor) allow a value to be set during object initialisation (including object initialisers) but not afterwards, supporting immutable-by-design types without `readonly` constructors. Primary constructors (C# 12) let you declare constructor parameters directly on the class declaration and use them throughout the class body, reducing boilerplate for simple data-holding types. Constructor chaining with `this(...)` and base constructor calls with `base(...)` reduce code duplication across overloads.
Example
// Classes, auto-properties, init-only, and primary constructors

// Traditional class with auto-implemented properties
public class Product
{
    public int    Id    { get; private set; }
    public string Name  { get; set; }
    public decimal Price { get; set; }

    // Primary fields computed from constructor args
    public string Category { get; init; }

    public Product(int id, string name, decimal price, string category)
    {
        Id       = id;
        Name     = name;
        Price    = price;
        Category = category;
    }

    public override string ToString() =>
        $"[{Id}] {Name} ({Category}) — ${Price:F2}";
}

var p = new Product(1, "Laptop", 999.99m, "Electronics");
Console.WriteLine(p);

// Object initialiser — sets public settable properties
var p2 = new Product(2, "Phone", 699.99m, "Electronics")
{
    Name = "Smartphone"   // can override in initialiser
};
Console.WriteLine(p2);

// C# 12 primary constructor (great for simple types)
public class Point(double x, double y)
{
    public double X { get; } = x;
    public double Y { get; } = y;
    public double DistanceTo(Point other) =>
        Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));
    public override string ToString() => $"({X}, {Y})";
}

var a = new Point(0, 0);
var b = new Point(3, 4);
Console.WriteLine($"Distance: {a.DistanceTo(b)}"); // 5