private string empName; Public string Empname { get { return empName; } set { empName= value; } }
Table of Contents
C# Automatic property
But, C# 3.0 onwards Properties can be declared simply without explicitly declaring the corresponding private member variable.
From C# 9, the ability to implement init accessors as auto-implemented properties has also been introduced.
In C# Automatic property is a property that has an automatically produced backing field that is generated by the compiler.
Primitive getters and setters that only return the value of the backing field are avoided which can save development time by allowing to not write that code.
We can utilize attributes in many circumstances for properties, but we generally prefer properties that are common across several .NET technologies.
Rest will be taken care of internally during compilation. This reduces no of lines of code and improves the development speed.
Public string EmpName { get; set}
C# Automatic Property After Compilation
After compilation the compiler produces the code of automatic property as below.
[CompilerGenerated] private string <EmpName>k__BackingField; public string EmpName { [CompilerGenerated] get { return <EmpName>k__BackingField; } [CompilerGenerated] set { <EmpName>k__BackingField = value; } }
Auto-implemented properties in C# 6.0 and higher versions, we can initialize in a similar fashion as fields like
//Automatic Property C# 6, assigning public string EmpName { get; set; } = "Rajeev";
Summary
This article gave you an idea of how to use Automatic Property in C#.I hope this was helpful for you. Please share your opinions in the comment section below.
You may also be interested in reading Object Initializers in C#
Leave a Reply