A Lesser-Known C# Feature: Nested Object Initializers
I've been writing C# for quite some time now, but only recently found out about the "nested object initializers" syntax in C#. Nested object initializers elegantly solve problems for which I've previously used workarounds. It's not a new feature; it was introduced in C# 3.0, under section 184.108.40.206 of the language specification:
An object initializer after the equals sign is a nested object initializer, i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property.
C# 7 local functions provide a more intuitive syntax over creating verbose System.Func delegates, as well as being more capable (they support ref and out parameters, async, generics, etc). In addition, some articles have mentioned that local functions compile down to normal methods, thus reducing GC allocations when compared to System.Func.
I was curious about that last part. How does it work? Let's open up the dotPeek decompiler and find out!
First, here's a simple test program using a local function: