Denis
Denis

Reputation: 12077

Setting a property without a setter. How is this not a compile error?

I have a class

 public class Settings : ProviderSettings {
        internal Settings(MyProvider provider) {
            this.Provider = provider;
            LoadFromConfig();
        }

        protected override IProvider Provider {
            get;
        }
}

The ProviderSettings class is:

 public abstract class ProviderSettings {
          protected abstract IProvider Provider { get; }
 }

In Visual Studio 2015 I don't get a compile error when I target .NET 4.0. I would imagine that I should have received a compile error saying that "Provider is read-only and can't be set". Why is the compiler allowing this?

Upvotes: 1

Views: 745

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

If you don't specify setter, then backing field of getter-only auto-property is implicitly declared as readonly. You can initialize it from constructor or using property initializer. This is a new feature of C# 6.

So actually your code will be compiled as

public abstract class ProviderSettings
{
    protected abstract IProvider get_Provider();
    // there is no property setter
}

public class Settings : ProviderSettings
{
    private readonly IProvider _provider;

    internal Settings(MyProvider provider) {
        _provider = provider; // assignment directly to backing field
        LoadFromConfig();
    }

    protected override IProvider get_Provider()
    {
        return _provider;
    }
    // there is no property setter
}

Related part of C# 6 Language Specification (draft):

If the auto-property has no set accessor, the backing field is considered readonly. Just like a readonly field, a getter-only auto-property can also be assigned to in the body of a constructor of the enclosing class. Such an assignment assigns directly to the readonly backing field of the property.

Upvotes: 5

Related Questions