C# Feature – Primary constructors
Overview
Section titled “Overview”Primary constructors let you declare constructor parameters directly on classes/structs, reducing boilerplate.
Introduced In
Section titled “Introduced In”C# 12 (2023)
Before
Section titled “Before”class Order{ public int Id { get; } public Order(int id) { Id = id; }}
class Order(int id){ public int Id { get; } = id;}
Annotated Example
Section titled “Annotated Example”record User(string Id, string Email);
Longer Example
Section titled “Longer Example”// A simple data carrier using a primary constructorpublic 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}"); }}
// Usagevar rabbit = new Rabbit("Bugs", 2, 2.5, "Brown", "Holland Lop", true);rabbit.Print();
Gotchas & Best Practices
Section titled “Gotchas & Best Practices”- Keep the constructor small; move logic to methods as needed.
Further learning
Section titled “Further learning”- Video: Primary Constructors overview (YouTube) — https://www.youtube.com/watch?v=72nt0Ds2478&t=3s
Related Features
Section titled “Related Features”Version Notes
Section titled “Version Notes”- Works with
required
andinit
.