Home > Backend Development > C++ > What Does `=>` Mean in C# Expression-Bodied Members?

What Does `=>` Mean in C# Expression-Bodied Members?

Mary-Kate Olsen
Release: 2025-01-30 23:26:11
Original
707 people have browsed it

` Mean in C# Expression-Bodied Members? " /> What Does `=>
</p> <性>

When encountering the following code:

It is important to understand that this is not Lambda expression, but a member of an expression.

public int MaxHealth =>
        Memory[Address].IsValid ? 
        Memory[Address].Read<int>(Offs.Life.MaxHp) : 
        0;
Copy after login
<达> Member of the expression

When the compiler encounters a member of the expression body, it will convert it to a getter:

<达> Members of the expression body and fields with initialization device

public int MaxHealth
{
    get
    {
        return Memory[Address].IsValid ? Memory[Address].Read<int>(Offs.Life.MaxHp) : 0;
    }
}
Copy after login
The difference between the expression of the expression and the fields with the initialization device can be explained by comparing the following content:

The expression of the expression is a getter that calls it every time you access the attribute. On the other hand, the field is initialized once when instantiated.

<法> Grammar candy
// 表达式体成员属性
public int MaxHealth => x ? y : z;
Copy after login
// 带有字段初始化器的字段
public int MaxHealth = x ? y : z;
Copy after login

The members of the expression are pure grammar sugar, and there is no additional function except the existing function. They provide the following content with a simpler syntax to attribute members:

No Return statement (hidden return expression)

No sentence block (the main body is a single expression)

No need to "get" keywords (hidden by the grammar of the expression of the expression)
  • Additional description
  • The members of the expression body are also suitable for indexes, methods, operators, constructors, and endors (in C# 7.0 or higher).

They are not suitable for nested types, events or fields. Although they are similar to lambda expressions in "= & gt;", they are not real Lambda expressions. Members of the expression body only indicate that the compiler generates a specific member behind the scenes.

    The above is the detailed content of What Does `=>` Mean in C# Expression-Bodied Members?. For more information, please follow other related articles on the PHP Chinese website!

    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
    Latest Articles by Author
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template