C# > Language Features by Version > C# 6 to C# 12 Highlights > Primary Constructors (C# 12)
Primary Constructors in C# 12: Basic Example
This example demonstrates the fundamental syntax of primary constructors introduced in C# 12. It shows how to define a class with constructor parameters directly in the class declaration and how those parameters can be used within the class.
Code Example
Here, `Person` is defined with `(string firstName, string lastName)` directly after the class name. These are the primary constructor parameters. The `FullName` property and the `Greet` method can then use these parameters. Note that these parameters are implicitly available as private fields within the class.
public class Person(string firstName, string lastName)
{
public string FullName => $"{firstName} {lastName}";
public void Greet()
{
Console.WriteLine($"Hello, my name is {firstName} {lastName}.");
}
}
Concepts Behind the Snippet
Primary constructors provide a more concise way to define constructors, especially when the primary purpose of the constructor is to initialize properties. They eliminate boilerplate code typically associated with traditional constructors where you declare parameters, assign them to fields, and so on. C# 12 effectively allows you to declare and initialize fields directly within the class declaration.
Real-Life Use Case
Imagine a data transfer object (DTO) that simply holds data retrieved from a database or an API. Primary constructors are perfect for such scenarios. You can quickly define the DTO with the required properties in the constructor without writing extensive initialization code.
Best Practices
Use primary constructors when the main purpose of the constructor is to initialize properties. Avoid using them if the constructor requires complex logic or extensive validation beyond simple assignment.
When to Use Them
When you need a quick and easy way to create a class that primarily holds data. DTOs, configuration classes, and simple data models are great candidates.
Pros
Cons
FAQ
-
Are primary constructor parameters automatically private fields?
Yes, primary constructor parameters are implicitly available as private fields within the class. You don't need to explicitly declare them as fields unless you need to modify their values after initialization (in which case, you'd create a backing field and initialize it with the parameter's value). -
Can I use primary constructors with inheritance?
Yes. The derived class can call the base class's primary constructor in its own primary constructor using the `base` keyword, passing in any required parameters.