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
- DTOs (Data Transfer Objects)
- Model classes with no constructor logic
- Immutable types
📌 Limitations
- Can't add validation or logic in constructor signature
- No support for constructor overloading
- Requires .NET 8 / C# 12+ for
classsupport
🏠 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
- Ensure your project uses C# 12+ or a preview-enabled SDK
- Use the syntax
class ClassName(type param1, ...) - 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.
⚠️ Use regular constructors if you need validation, logging, or multiple overloads.

Comments
Post a Comment