Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's this strange C# syntax and how do I build it? [duplicate]

Tags:

syntax

c#

c#-6.0

When reading a project, I found some strange C# code:

public class F : IElement
{
    public int CurrentHp { get; } = 10;
    public bool IsDead => CurrentHp <= 0;
}

Normally I would write something like:

public class F : IElement
{
    public const int CurrentHp = 10;
    public bool IsDead
    {
        get { return CurrentHp <= 0; }
    }
}

My Visual Studio 2013 also cannot recognize the first example.

What is this syntax and what should I do to make this project buildable?

like image 576
kuang Avatar asked Feb 24 '16 06:02

kuang


4 Answers

=> is a new operator in C# 6 and indicates an Expression Bodied Function to use for that getter.

Your two examples are synonymous as far as the compiler is concerned and merely return the value assigned. The => is syntactic sugar to make development a bit easier and require fewer lines of code to achieve the same outcome.

However, you won't be able to compile unless you update to VS2015 with the latest compiler version.

Edit:

As said by Philip Kendall and Carl Leth in the comments, the first lines in each are not exactly synonymous as public const int CurrentHp = 10; is a field and public int CurrentHp { get; } = 10; is a property. Although at a high level the outcome is the same (assigning a value of 10 to CurrentHp with the property only being settable in the class constructor), they differ in that:

With const int CurrentHp = 10, CurrentHp will always be 10, take up 4 total bytes, and can be accessed statically. int CurrentHp { get; } = 10defaults to 10, but can be changed in the constructor of F and thereby can be different per instance and cannot be accessed statically.

like image 168
Steve Avatar answered Oct 03 '22 15:10

Steve


It's C# 6 features: New Language Features in C# 6.

The first

public int CurrentHp { get; } = 10;

is Getter-only auto-propertiey.

The second

public bool IsDead => CurrentHp <= 0;

is Expression bodies on property-like function members.

like image 36
Kirill Avatar answered Oct 03 '22 14:10

Kirill


As other people said it's new C# 6 features. Check full list at 1

However more correctly this would translate to this in before C# 6:

public class F : IElement
{
    public int CurrentHp { get; private set };
    public bool IsDead { get { return CurrentHp <= 0; } }
    public F() { CurrentHp = 10; }
}

New Language Features in C# 6

like image 37
aiodintsov Avatar answered Oct 03 '22 16:10

aiodintsov


This is your code if you use C# 6:

public bool IsDead => CurrentHp <= 0;

It is just a property with a get, if use this operator =>.

In earlier versions you would write something like this:

public bool IsDead { get { return CurrentHp <= 0; } }
like image 40
daniel59 Avatar answered Oct 03 '22 14:10

daniel59