Primary constructors in C# 12 make it easier to define and initialize properties in classes or structs, significantly streamlining your code. Initially available only for records, this feature now applies to all types. Here's how it works.
Without Primary Constructors:
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public Employee(string name, int age)
{
Name = name;
Age = age;
}
}
var employee = new Employee("Raj", 30);
Console.WriteLine($"{employee.Name} is {employee.Age} years old.");
With Primary Constructors:
public class Employee(string name, int age)
{
public string Name { get; } = name;
public int Age { get; } = age;
}
var employee = new Employee("Raj", 30);
Console.WriteLine($"{employee.Name} is {employee.Age} years old.");
Traditional Constructor: Properties are defined and then initialized within the constructor.
Primary Constructor: Properties are declared and initialized directly in the class definition, which reduces boilerplate code and makes the class more concise.
The primary constructor feature simplifies your code by reducing verbosity, allowing you to concentrate on the core elements of your class definitions.