#252 – Automatic Properties

The typical syntax for a property implementation in C# is to define the public interface for the property and then have the implementation of the get and set accessors for the property read/write to a private backing variable.

        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

C# provides a shortcut for this structure through the use of automatic properties.  You can avoid declaring the private backing variable and implementing the get/set accessors by simply declaring the get/set accessors without a body.

        public string Name { get; set; }

When you declare a property this way, it appears exactly the same to any client code.  The underlying code generated by the compiler is also the same–a public property with a backing variable–but you don’t actually have access to the backing variable.

Advertisements

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

2 Responses to #252 – Automatic Properties

  1. Pingback: #702 – An Automatic Property Must Define Both get and set Accessors « 2,000 Things You Should Know About C#

  2. In Visual Studio you can use the “prop” code snippet to quickly write an automatic property.

    If you like the look of an explicit backing field, or you might have a need to enhance the implementation later you can use the “propfull” code snippet.

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 )

Connecting to %s

%d bloggers like this: