Primary Constructors
We mainly use constructor to initialize the values inside it. (Accept parameter values and assign those parameters to instance properties).
Before
public class PrimaryConstructorsBeforeCSharp6
{
public PrimaryConstructorsBeforeCSharp6(long postId, string postName, stringpostTitle)
{
PostID = postId;
PostName = postName;
PostTitle = postTitle;
}
public long PostID { get; set; }
public string PostName { get; set; }
public string PostTitle { get; set; }
}
After
public class PrimaryConstructorsInCSharp6(long postId, string postName, stringpostTitle)
{
public long PostID { get; } = postId;
public string PostName { get; } = postName;
public string PostTitle { get; } = postTitle;
}
In C# 6, primary constructor gives us a shortcut syntax for defining constructor with parameters. Only one primary constructor per class is allowed.
If you look closely at the above example, we moved the parameters initialization beside the class name.
You may get the following error “Feature ‘primary constructor’ is only available in ‘experimental’ language version.” To solve this, we need to edit the SolutionName.csproj file to get rid of this error. What you have to do is we need to add additional setting after WarningTag.
<LangVersion>experimental</LangVersion>
Feature ‘primary constructor’ is only available in ‘experimental’ language version
No comments:
Post a Comment