Back
Close

Auto-property initializers in C#

gpeipman
48.5K views

Auto-property initializers

Automatic properties is good feature in C# as we don’t have to declare variables for property values in our code. Instead we move this responsibility to compiler that automatically generated hidden backing field for property. New C# solves another problem – assigning default values to automatic properties when object is created.

This is how a

Moving to auto-property initializer

Now let's see how to assign value to Dummy property without using constructor for this.

But what about read-only auto-property? Is it supported? Try out and see.

Why it works? Auto-property has always backing field available although we don't see it in IDE. If we disassemble built library and remove pdb-file then we can see that there is hidden field that is internally used by .NET Framework. Assigning value to auto-property means assigning value to backing field.

References

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io