Introdcution
On November 12, 2014 Microsoft announced the release of Visual Studio 2015 on the day of Visual Studio Connect() from New York, USA where they announced many new features as well as enhancements with C# 6.0. So we should understand that a Primary Constructor is not applicable with C# 6.0 but we can do the same thing using Auto Implemented Properties Initializers.
Basically a Primary Constructor is a feature of C# that was announced with Visual Studio 2014 by which a class or structure can accept parameters in the class definition without a formal constructor declaration. But what we would like to say is that now it has been removed from Visual Studio 2015 Preview. So in C# 6.0 it's not possible to use a primary constructor. So before learning more about it let's see it with an example program.
Example
public class Square(double side)
{
public double Side{get;set;}
}
Note. The preceding program is written in Visual Studio 2014. That is fine but it gives a syntax error when we want to write this code in any other IDE except Visual Studio 2014. Let's do it with Visual Studio 2015 or any other IDE except Visual Studio 2014.
Primary Constructor with Visual Studio 2015.
With Visual Studio 2013.
Note. We saw that when we are writing the code of the Primary Constructor in Visual Studio 2015 as well as 2013, the same error is found in both IDEs. But the same line of code will run well in Visual Studio 2014.
What is the use of Primary Constructor?
- The main use of a primary constructor is to initialize the auto-implemented properties by the variable that are the parameter of the Primary Constructor.
- A primary constructor behaves like a default constructor because it shows the minimal required parameters.
Example
The following program is written in Visual Studio 2014.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PrimaryConstructor
{
public class Squre(double side)
{
public double Side { get; set; }=side;
//Area
public double AreaOfSquare()
{
return Convert.ToDouble(side*side);
}
static void Main(string[] args)
{
Square sq=new Square(15.8);
sq.AreaOfSquare();
}
}
}
Auto Implemented Properties Initializers
Now we can do the same work using auto implemented property Initializers that were announced by Microsoft on November 12, 2014 on the day of #vsconnect.
We can initialize the getter and setter properties together as well as getter only also.
Example
Initializing the getter and setter together.
public class Book
{
public string Title { get; set; }="Visual C# 6.0";
public string Auther{get;}="Microsoft";
}
Example
Initializing the getter only.
public class Book
{
public string Title { get; }="Visual C# 6.0";
public string Auther{get;}="Microsoft";
}
Output
Summary
In this article we learned about the Auto Implemented Properties Initializers and how it fullfills the requirements of a Primary Constructor.