Primary Constructors in .NET Core

Primary constructors offer a streamlined way to initialize properties directly from constructor parameters in C# classes and records. Introduced in C# 9 (for records) and extended further in C# 12 (preview for classes), they help eliminate boilerplate code in data-oriented types.

⚠️ Important: As of C# 12, primary constructors for class are still in preview. In production apps, they are currently supported only in record types.


🧠 What Is a Primary Constructor?

Instead of writing a full constructor and assigning properties, a primary constructor allows you to define parameters directly in the class or record header and use them inside the body.

public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age;
}

✨ Benefits of Primary Constructors

  • Less Code – Removes repetitive constructor boilerplate.
  • Immutability – Easily define read-only properties.
  • Inline Property Initialization – Clean class declarations.

💼 Example: Product Class

public class Product(string name, double price, string category)
{
    public string Name { get; } = name;
    public double Price { get; } = price;
    public string Category { get; } = category;

    public string DisplayName => $"{Category} - {Name}";
}

✅ Use Cases

📌 Limitations

  • Can't add validation or logic in constructor signature
  • No support for constructor overloading
  • Requires .NET 8 / C# 12+ for class support

🏠 Example: Address DTO

public class Address(string street, string city, string zipCode)
{
    public string Street { get; } = street;
    public string City { get; } = city;
    public string ZipCode { get; } = zipCode;
}

⚙️ How to Use Primary Constructors

  1. Ensure your project uses C# 12+ or a preview-enabled SDK
  2. Use the syntax class ClassName(type param1, ...)
  3. Use parameters inside the class body for fields or property initialization

📋 Summary

Primary constructors simplify your code, especially for small data-focused types like models and DTOs.
⚠️ Use regular constructors if you need validation, logging, or multiple overloads.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features