2
public override double TotalSpecialPower => 1000;

What does the => operator mean?

I know that => is a lambda expression, but I don't know what it means in public override double TotalSpecialPower => 1000;.

And also can anyone explain to me the get and set and how they work in the following code?

private int _health = 100;
public int Health
{
    get => _health;
    set { _health = value; CaluateHeath(); }
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
ZCoder
  • 2,155
  • 5
  • 25
  • 62
  • 1
    @RaymondChen That QA refers to a lambda or anonymous method, not to expression-bodied members which the OP is referring to. – Dai Apr 21 '19 at 01:53
  • @Dai I was going to edit the duplicate list, but your reopen now blocked me. This is a duplicate of https://stackoverflow.com/questions/54098375/expression-bodied-members-vs-lambda-expressions – Camilo Terevinto Apr 21 '19 at 01:55
  • I appreciate both of you for the answers. – ZCoder Apr 21 '19 at 01:59

2 Answers2

8

=> is used for lambda-functions as you mentioned. It's also used for expression-bodied members.

The documentation on expression-bodied members is available here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

  • C# 6.0 in 2015 added support for expression-bodied methods.
  • C# 7.0 in 2016 added support for expression-bodied properties and other members.

  • In methods and property get blocks, it's equivalent to { return X; }.

  • In properties:
    • If the property has a single expression-body, then it's equivalent to declaring a getter-only get { return X; } property.
    • If the proeprty has an explicit get, then it's equivalent to ``

So this:

public int Health
{
    get => _health;
    set {  _health = value; CaluateHeath(); }
}

Is equivalent to:

public int Health
{
    get { return _health };
    set {  _health = value; CaluateHeath(); }
}

And this:

public override double TotalSpecialPower => 1000;

Is equivalent to:

public override double TotalSpecialPower
{
    get { return 1000; }
}

And this (note the parentheses):

public override double TotalSpecialPower() => 1000;

Is equivalent to:

public override double TotalSpecialPower()
{
    return 1000;
}
Dai
  • 141,631
  • 28
  • 261
  • 374
2

It’s all about Expression Bodies. Properties are just syntactic sugar to make method calls look like normal field assignments and gets.

A normal property had a get and set with curly backs to a block of code. That can be a lot of syntax for a one liner. So I’m the most recent versions of the C# language, you can use Expression Bodies (fat arrows), like with lambdas, for your getters and setters.

I hope that helps.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members