Home > Backend Development > C++ > How Can I Assign Initial Values to C# Auto-Properties?

How Can I Assign Initial Values to C# Auto-Properties?

DDD
Release: 2025-01-30 03:26:08
Original
368 people have browsed it

How Can I Assign Initial Values to C# Auto-Properties?

The initial value assignment method of the automatic attribute of the automatic attribute

C #'s automatic attribute provides a simple syntax to define the attributes with automatic Getter and Setter. However, the assignment of automatic attributes needs to be traditionally used to use a constructor or restore the old attribute grammar.

Traditional methods

Construct function initialization:

Initialize automatic properties in the constructor to ensure that it is valuable when the object is created.
  • Old attribute grammar:
The use of complete attribute grammar allows the initial value of the value in the Getter and Setter method.
<code class="language-csharp">class Person
{
    public Person()
    {
        Name = "初始名称";
    }

    public string Name { get; set; }
}</code>
Copy after login
  • C# 6.0's inner joint initialization device
In C# 6.0 and higher versions, a simpler method can be used to assign the initial value of the automatic attribute. This grammar allows the initial value in the inner coupling:
<code class="language-csharp">private string name = "初始名称";

public string Name 
{
    get 
    {
        return name;
    }
    set
    {
        name = value;
    }
}</code>
Copy after login

DefaultValueAttribute's limitations

DefaultValueAttribute is mainly used for Visual Studio designer to specify the default value displayed in the IDE. It does not affect the generated IL, nor is it used to initialize the attribute during runtime.

<code class="language-csharp">public int X { get; set; } = x; // C# 6 或更高版本</code>
Copy after login
In short, the inner United initialization of the inner United initializer introduced in C# 6.0 provides a direct and concise method to assign the initial value of the automatic attribute, avoiding the need to manually initialize or use the old attribute syntax in the constructor.

The above is the detailed content of How Can I Assign Initial Values to C# Auto-Properties?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template