Primary Constructors in C# 12
Introduction
Before dive into Primary Constructors, let's take a quick look at how class constructors work in C#. In C# constructor is a special method that is called when an object of a class is created. Constructors are used to initialize the state of an object, 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
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 parameterless constructor, so if you try to create an object using the default constructor, you'll get a compiler error.
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 new feature that simplify the process of defining and initializing class properties in C# 12.
In summary, Primary Constructors offer a cleaner and more concise way to initialize properties in C# classes, which help developers write more readable, maintainable code.
Comments
Post a Comment