I'm too stupid for the new VS2015 C# syntax

I just found out (the hard way of course) that


is not the same as 

```cs]public IDictionary<string, XsStyle> Styles { get; } = new Dictionary<string, XsStyle>();[/code


In fact I knew before that it is not the same, but it happened anyway :wall:

@ Reinhard Ostermeier - Please explain the subtle difference.

In the first case every time you use property Styles a new dictionary will be created.
In the second case a field is generated and constructed during initialization. The property will return that field.

2 Likes

Yep, that’s the difference.
And I felt so smart when I wrote it at first.

And even more stupid when I found out my mistake.

When have doubts check the IL code.
I found LINQPad to be invaluable tool for its many features. One of them is built-in IL viewer.

3 Likes

I have never used the => with C#… I Need to learn about that!

@ leforban - Using a lambda expression to implement the getter only auto-property is one of the new features added in C# 6.0

On its own lambdas ( => ) been around for awhile now :wink:
If you haven’t had a chance to use them yet, definitely start sooner to learn about them than later.

@ leforban - If you have ReSharper installed, it can convert forward and backward from using lambdas to classic code in many situations.
This is a great tool to see where different coding styles are possible.
So far I have not found a single situation where the ReSharper change would have changed behavior of my code. and in some cases I checked very exactly.