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

=> 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.

Leave a Comment

tech