I had an issue yesterday with some code I found on the internet and realized that the implementation was probably not exactly what was intended.
Let’s look at a much simplified version of that code that illustrates the problem:
If you run this code, you will find that the
StaticResources.Colors is empty. At first glance, one would expect the
StaticResources.Colors to have 3 elements. What’s going on? Is C# broken?
The problem here is that the property
Colors in the
SharedResources class is initialized using what is called an
Expression bodied member and was introduce in
C#6. It’s a mouth full I know but it is nothing else than syntaxic sugar for:
What should have been used instead is an
initializer for read-only auto-property which was also introduce in
which is equivalent to the following code
With this little change, the auto-property
Colors is only initialized once and the code works as expected.
Don’t get me wrong. I love the new syntaxic features that shipped with
C#6 and I use them all the time. The code intent is clear and we can reduce the syntaxic noise greatly.
That being said Friends, it’s not always easy to find those mistakes on real code. So beware!