julian
julian

Reputation: 4714

C# - constant property is equivalent to lambda expression?

I picked up C# again, came back after a long work in Java, and as you may expect, I got very interested in properties(oh the Java burden), therefore I started to explore them a bit and came up with this.

private static float Width {
    get { return 0.012f; }
}

After a bit of tinkering, I realized this works too(lambda expression?).

private static float Width => 0.012f;

Now please help a fellow Java developer here to understand what is exactly the difference? What the former can do that the latter cannot and vice versa.

Upvotes: 11

Views: 4276

Answers (3)

chsword
chsword

Reputation: 2062

There are equal.

private static float Width => 0.012f;

The Width is a getter only property just like your first example;
The difference is merely only syntactic sugar.

ref: https://github.com/dotnet/roslyn/wiki/Languages-features-in-C%23-6-and-VB-14

Upvotes: 2

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149548

what is exactly the difference?

Both ways define a getter only property. The latter simply uses C# 6's new feature called "Expression Bodied Members", specifically these are "Expression Bodied Properties", which allow you to use the fat arrow syntax and are merely syntax sugar.

If you look at what the compiler generates, you'll see:

private static float Width
{
    get
    {
        return 0.012f;
    }
}

Which is identical to your getter only declaration.

These can also be applied to one-liner methods as well:

public int Multiply(int x) => x * x;

Upvotes: 14

Karl Gjertsen
Karl Gjertsen

Reputation: 4928

This is a simplification of the language under C# 6.0 and are called 'Expression Bodied Functions / Properties'.

The idea is to simplify the syntax and allow you to set values for functions and properties in a shorter format.

Visual Studio magazine has an article on it here: https://visualstudiomagazine.com/articles/2015/06/03/c-sharp-6-expression-bodied-properties-dictionary-initializer.aspx

Upvotes: 2

Related Questions