Skip to content

C# Feature – Primary constructors

Primary constructors let you declare constructor parameters directly on classes/structs, reducing boilerplate.

C# 12 (2023)

class Order
{
public int Id { get; }
public Order(int id) { Id = id; }
}
class Order(int id)
{
public int Id { get; } = id;
}
record User(string Id, string Email);
// A simple data carrier using a primary constructor
public class Rabbit(string name, int age, double weight, string color, string breed, bool isDomesticated)
{
public string Name { get; set; } = name;
public int Age { get; set; } = age;
public double Weight { get; set; } = weight;
public string Color { get; set; } = color;
public string Breed { get; set; } = breed;
public bool IsDomesticated { get; set; } = isDomesticated;
public void Print()
{
Console.WriteLine($"Name: {Name}");
Console.WriteLine($"Age: {Age}");
Console.WriteLine($"Weight: {Weight}");
Console.WriteLine($"Color: {Color}");
Console.WriteLine($"Breed: {Breed}");
Console.WriteLine($"IsDomesticated: {IsDomesticated}");
}
}
// Usage
var rabbit = new Rabbit("Bugs", 2, 2.5, "Brown", "Holland Lop", true);
rabbit.Print();
  • Keep the constructor small; move logic to methods as needed.
  • Works with required and init.