The automatic attribute of C# provides a simple way to define attributes, without separate fields and explicit attribute accessors. However, the initial value of the initial value is required to use the constructor or the traditional attribute syntax.
Starting from C# 6.0, there is a more direct method to set the initial value of the automatic attribute:
Initialization of Neilian
Here, the attribute X is initialized to 0 during the compilation period, and there is no need to perform additional initialization or use the traditional attribute grammar in the constructor.
public int X { get; set; } = 0;
<于> The initialization of the constructive function:
This method needs to be explicitly initialized in the constructor, which may lead to a lengthy and repeated initialization code. <统> Traditional attribute grammar:
public Person() { Name = "Initial Name"; } public string Name { get; set; }
Although this method provides an initial value, it needs to create a supporting field, which may introduce unnecessary model code and maintenance overhead.
private string name = "Initial Name"; public string Name { get { return name; } set { name = value; } }
The above is the detailed content of How Can I Initialize C# Auto-Properties?. For more information, please follow other related articles on the PHP Chinese website!