C# 12 introduces multiple amazing features. But, one of the features which I liked most is the Primary Constructor.
What is a Constructor?
We are all familiar with the constructor. It is a special method which we use to initialize the object of a class. The Constructor executes as soon as we create the object of that class.
The general syntax of creating a constructor:
public class MyClass
{
public MyClass() { }
}
Here, we are creating a constructor for the class MyClass
. The constructor name must be the same as the class, and it doesn’t have any return type.
What is a Primary Constructor?
The Primary Constructor concept came into existence in C# 12 along with .NET 8.
Primary Constructor enables us to remove the constructor method and add its parameters to the class declaration itself.
Let’s understand this with a code snippet, first, we will understand the traditional way to create a parameterized constructor:
public class Product
{
public string Name { get; set; }
public Product(string name)
{
Name = name;
}
}
Here, We are creating a constructor of the class Product
. And, we are assigning value to the property using the constructor.
Let’s see how we can implement Primary Constructor:
public class Product(string name)
{
public string Name { get; set; } = name;
}
In this code snippet, we are adding a parameter to the class Product
and assigning the parameter to the property Name
. This is the main use of the Primary constructor.
So, while initializing the class with the primary constructor we must pass the parameter.
Let’s see how to initialize a class with the primary constructor:
var product = new Product("Laptop");
As we have a class Product
which accepts a parameter of type string
. So, we are passing the string
value while initializing the class.