Back
Close

Auto-property initializers in C#

gpeipman
9,540 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

using System;
class MyClass
{
public string Dummy { get; set; }
public MyClass()
{
Dummy = "I'm dummy property";
}
}
class Program
{
static void Main()
{
var myClass = new MyClass();
Console.WriteLine(myClass.Dummy);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Moving to auto-property initializer

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

using System;
class MyClass
{
public string Dummy { get; set; } = "I'm dummy property";
}
class Program
{
static void Main()
{
var myClass = new MyClass();
Console.WriteLine(myClass.Dummy);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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

using System;
class MyClass
{
public string Dummy { get; } = "I'm dummy property";
}
class Program
{
static void Main()
{
var myClass = new MyClass();
Console.WriteLine(myClass.Dummy);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants