Skip to main content

Posts

Showing posts with the label C# primary constructor

C# Primary Constructors: Simplify Classes (C# 12 Guide)

Learn C# primary constructors with runnable examples, best practices and pitfalls. Cut boilerplate in C# 12 classes and DI services — start coding today. If you have ever written a service class in .NET and felt like you were typing the same parameter name three times — once in the constructor signature, once in the assignment, once in the field declaration — then the C# primary constructor is the feature you have been waiting for. Introduced in C# 12 (shipped with .NET 8 in November 2023), primary constructors let you declare constructor parameters directly on the class or struct declaration and use them anywhere in the body. This tutorial covers the syntax, the semantics that trip people up, real-world dependency injection patterns, and the pitfalls that static analysis will not always catch. What Is a C# Primary Constructor? A primary constructor is a parameter list attached directly to a type declaration. Those parameters are in scope for the entire class body — field init...