Auto-property initializers in C#

gpeipman
1,006 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content