What is the => assignment in C# in a property signature

前端 未结 7 1238
执念已碎
执念已碎 2020-11-22 00:29

I came across some code that said

public int MaxHealth => 
         Memory[Address].IsValid ? 
         Memory[Address].Read(Offs.Life.MaxHp)          


        
7条回答
  •  野的像风
    2020-11-22 01:23

    It is called Expression Bodied Member and it was introduced in C# 6. It is merely syntactic sugar over a get only property.

    It is equivalent to:

    public int MaxHealth { get { return Memory[Address].IsValid ?
                                 Memory[Address].Read(Offs.Life.MaxHp) : 0; }
    

    An equivalent of a method declaration is avaliable:

    public string HelloWorld() => "Hello World";
    

    Mainly allowing you shortening of boilerplate.

提交回复
热议问题