Skip to content

Auto property initializer C# 6.0code reduction

Allow auto-implemented 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. C# 6.0 also allows getter-only auto-properties ({ get; }) which can only be set by an initializer or in a constructor, giving you truly read-only properties without a backing field.

Code ​

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

    public JobRequest()
    {
    }

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

    public JobRequest()
        : this("New Job")
    {
    }

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

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
    • Move the code to a shared method, which only works with settable properties and not readonly fields
  • Before C# 6.0 the closest thing to a read-only auto-property was { get; private set; }, which the class itself can still change at any time

More information ​

Powered by Intracia