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?
=>
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 be10
, take up 4 total bytes, and can be accessed statically.int CurrentHp { get; } = 10
defaults to10
, but can be changed in the constructor ofF
and thereby can be different per instance and cannot be accessed statically.
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.
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
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With