In my previous post I explain about Auto Property Initializer in C# 6.0. Now lets see another new feature in C# 6.0 which is Primary constructor.
First we will see the following code.
here we have a class which has a property with a private setter and assigning the value for the name property inside the constructor.
Now in C# 6.0 you can write the above code in a more simplified manner as follows.
This is what is called primary constructor in C# 6.0 . Notice the parameters added just right of the class definition. This tells the compiler to add a constructor to the Country class with one parameters: name. So we don’t need to create separate constructor with parameters and then assign the values to the property , compiler do all those for us.
For one class only one primary constructor is allowed. If you want to have constructors with some more parameters you can create new constructor and also call the primary constructor inside it. See the following example.
Here when you call the constructor with two parameters it will assign the value to the property “Regions” and it has call the primary constructor it will set the value to the property “Name”. Hope you understand the concept behind this.
Hope this is helpful.
Happy Coding !!!!!!