Hey everyone, have you heard about the new feature in C# 12.0 called Primary Constructors? It's super exciting!
Previously, when we wanted to create a class in C#, we had to define a constructor explicitly. This could sometimes lead to boilerplate code and make the code harder to read. But with Primary Constructors, things are about to change!
Primary Constructors simplify the process of creating class constructors by allowing us to declare them directly in the class declaration itself. We no longer need to define a separate constructor block. This not only improves readability but also reduces the amount of code we need to write.
To define a Primary Constructor, we use the init modifier before the parameter list. This indicates that the constructor can only be called during object initialization and not modified later. This helps enforce immutability and ensures that the object state remains constant after initialization.
Here's a small example to illustrate how Primary Constructors work:
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
In the above code, we define a Person class with two properties: FirstName and LastName. Instead of a separate constructor declaration, we can directly initialize these properties in the class declaration itself using the Primary Constructor syntax. The init modifier ensures that the values cannot be modified once initialized.
To use the Primary Constructor, we can simply create an instance of the Person class and provide the required arguments, like this:
var person = new Person("John", "Doe");
And voila! We have created a Person object with the provided values, without any additional boilerplate code.
Primary Constructors in C# 12.0 are a fantastic addition to the language, making our code cleaner, more concise, and enforcing immutability. They provide a convenient way to define constructors directly in the class declaration, reducing the need for extra code blocks. So, let's embrace this new feature and enjoy writing more elegant and readable C# code!
Top comments (2)
This is not what primary constructors are, and the one you are showcasing in your example uses regular constructors that exist way before C# 12.
A primary constructor, as stated in the docs is a constructor that used to be restricted to
recordtypes only and is now available forclassandstructtypes as well.In your example, using a primary constructor for
Personwould be writting your class this way:yes, indeed, you are right!