C # - constant property equivalent to lambda expression?

I took C # again, returned after a long work in Java, and, as you can expect, I was very interested in properties (the burden of Java), so I started to study them a bit and came up with this.

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

After messing around a bit, I realized that this works too (lambda expression?).

 private static float Width => 0.012f; 

Now, please help one Java developer understand here what exactly is the difference? What the former can do, what the latter cannot and vice versa.

+5
source share
3 answers

what is the difference?

Both methods define a property for getter only. The latter simply uses the new C # 6 feature called "Expression Bodied Members" , in particular it is "Expression Bodied Properties", which allows you to use fat arrow syntax and just syntactic sugar.

If you look at what the compiler generates, you will see:

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

What matches the ad is only for the recipient.

They can also be applied to single-layer methods:

 public int Multiply(int x) => x * x; 
+8
source

There are equals.

 private static float Width => 0.012f; 

Width is a property only for getter, like your first example;

The difference is just syntactic sugar.

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

+2
source

This simplification of the language under C # 6.0 is 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.

There is an article in the Visual Studio magazine about this: https://visualstudiomagazine.com/articles/2015/06/03/c-sharp-6-expression-bodied-properties-dictionary-initializer.aspx

+2
source

Source: https://habr.com/ru/post/1236411/


All Articles