#702 – An Automatic Property Must Define Both get and set Accessors

When you define an automatic property, you must include both get and set accessors.

        public string Name { get; set; }

It wouldn’t make sense to omit either accessor, since they are the only mechanism for reading from or writing to the property.

Although you can’t strictly create a read-only or write-only automatic property, you can use access modifiers so that the property is effectively read-only or write-only, from outside the class.

        // Automatic property that is read-only from outside class
        public string Temperament { get; protected set; }

        // Automatic property that is write-only from outside class
        public string Password { protected get; set; }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #702 – An Automatic Property Must Define Both get and set Accessors

  1. Emilio says:

    Hi Sean.

    IMO you can create a readonly property by only include get accessor:

    public string Temperament { get; }

    Regards.

    • Sean says:

      Emilio,

      Actually, automatic properties must define both get and set accessors. The line you show above would result in a compiler error.

      You can, however, implement a read-only property by defining only a get accessor, if you’re defining a regular property, rather than an automatic property. So in your example, if you added a body to the get accessor, it would be allowed.

      • Emilio says:

        Yes, you’re absolutly right the get accessor must have a body to work so it’s not an automatic property.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: