C# 6.0 - Auto-Property Changes
This is the second in a series of posts on the new features that are coming in C# 6.0. There have been a few small improvements to Auto-Properties.
Auto-Property Initializers
I hinted at this feature in my last post on Primary Constructors. Auto-Properties were introduced way back in C# 3.0, but unlike other members, you had to initialize their values in the constructor.
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public Product()
{
Name = "Toy Car";
Price = 9.99m;
}
}
In C# 6.0, you can now initialize the properties where they are declared.
public class Product
{
public string Name { get; set; } = "Toy Car";
public decimal Price { get; set; } = 9.99m;
}
Getter Only Auto-Properties
You could always declare the setter of an auto-property private or protected to prevent it from being used outside of the class.
public decimal Price { get; private set; }
Now you can omit the setter and it makes the underlying field read-only, so you can only set it in the constructor. This is a great feature for creating and enforcing imutable classes.
public class Product
{
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
public string Name { get; }
public decimal Price { get; }
}
If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.