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)
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
requiredandinit.