Skip to content

Auto property initializer C# 6.0code reduction

Allow automatic properties to have an initial value.

Previously auto-implemented properties C# 3.0 required initial values to be initialized in the constructors.

This was a bit of a pain when you had multiple constructors as you had to either initialize them in multiple places or carefully chain the constructors together with : this().

In C# 6.0 you can initialize them inline by simply appending = value; to the definition.

Code

C#
class JobRequest
{
    public Guid Id { get; private set; } = Guid.NewGuid();
    public string Name { get; set; } = "New Job";
    public DateTime Created { get; private set; } = DateTime.UtcNow;

    public JobRequest()
    {
    }

    public JobRequest(string name)
    {
        Name = name;
    }
}
C#
class JobRequest
{
    public Guid Id { get; private set; }
    public string Name { get; set; }
    public DateTime Created { get; private set; }

    public JobRequest()
        : this("New Job", DateTime.UtcNow)
    {
    }

    public JobRequest(string name, DateTime created)
    {
        Id = Guid.NewGuid();
        Name = name;
        Created = created;
    }
}

Notes

  • This is especially useful with multiple constructors as you either had to:
    • Repeat the initialization code across constructors
    • Put the initialization logic in the constructor with the most args and chain the others through it (picture above in Before)
    • Move the code to a shared method - this only works if you do not have read-only properties

More information