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

前端 未结 7 1117
执念已碎
执念已碎 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:15

    Ok... I made a comment that they were different but couldn't explain exactly how but now I know.

    String Property { get; } = "value";
    

    is not the same as

    String Property => "value";
    

    Here's the difference...

    When you use the auto initializer the property creates the instance of value and uses that value persistently. In the above post there is a broken link to Bill Wagner, that explains this well, and I searched the correct link to understand it myself.

    In my situation I had my property auto initialize a command in a ViewModel for a View. I changed the property to use expression bodied initializer and the command CanExecute stopped working.

    Here's what it looked like and here's what was happening.

    Command MyCommand { get; } = new Command();  //works
    

    here's what I changed it to.

    Command MyCommand => new Command();  //doesn't work properly
    

    The difference here is when I use { get; } = I create and reference the SAME command in that property. When I use => I actually create a new command and return it every time the property is called. Therefore, I could never update the CanExecute on my command because I was always telling it to update a new reference of that command.

    { get; } = // same reference
    =>         // new reference
    

    All that said, if you are just pointing to a backing field then it works fine. This only happens when the auto or expression body creates the return value.

提交回复
热议问题