Introduction
C# 12 introduces a new feature called Primary Constructors. This feature aims to simplify the initialization of properties in classes, especially for classes with many properties. This article will explore Primary Constructors and see how they work.
Before diving into Primary Constructors, let's look at how class constructors work in C#. In C#, a constructor is a special method called when a class object is created. Constructors are used to initialising an object's state, which typically involves setting the values of the class properties.
Here's an example of a typical class with a constructor in C#,
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime HireDate { get; set; }
public decimal Salary { get; set; }
public Employee(string firstName, string lastName, DateTime hireDate, decimal salary)
{
FirstName = firstName;
LastName = lastName;
HireDate = hireDate;
Salary = salary;
}
}
What are Primary Constructors?
A Primary Constructor is a new feature in C# 12 that allows you to define and initialize properties directly within the constructor parameter list. This feature eliminates the need for repeated code and makes your code more concise and readable.
Using Primary Constructors
Let's start with an example of using Primary Constructors with an Employee class. Here's how you would define an Employee class using a Primary Constructor,
public class Employee(string firstName, string lastName, DateTime hireDate, decimal salary)
{
public string FirstName { get; init; } = firstName;
public string LastName { get; init; } = lastName;
public DateTime HireDate { get; init; } = hireDate;
public decimal Salary { get; init; } = salary;
}
In this example, we've defined an Employee class with four properties: FirstName, LastName, HireDate, and Salary. We've also used the init keyword to make the properties read-only and initialized them directly within the Primary Constructor's parameter list.
Here's how you would create a new Employee object using the Primary Constructor.
var employee = new Employee("John", "Doe", new DateTime(2020, 1, 1), 50000);
The Employee the object is created with the firstName, lastName, hireDate, and salary parameters, which are used to initialize the corresponding properties.
Notice that the Employee class doesn't have a constructor method with a parameterless constructor, so you'll get a compiler error if you try to create an object using the default constructor.
Primary Constructors work well with classes that have many properties, as they reduce the amount of boilerplate code required to initialize them. Additionally, using Primary Constructors makes your code more readable and reduces the risk of errors caused by missing or incorrectly ordered initialization statements.
Conclusion
Primary Constructors are a new feature that simplifies defining and initializing class properties in C# 12.