Caveman's Blog

My commitment to learning.

Dotnet: Automatic properties

leave a comment »


In this blog post I will show you how Automatic properties (Auto-implemented Properties) are reinterpreted by the compiler. Automatic properties is a new coder friendly style introduced by Microsoft since Dotnet 3.0. I will directly quote what Microsoft has to say about these properties: Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property’s get and set accessors [1]. Following is an Employee class with a property.

    public class employee
    {
        //Auto-Implemented property
        public string Name { get; set; }
    }

The above code will be reinterpreted by the compiler as follows (I was able to extract this code using DotNet Reflector):

    public class employee
    {
        // Fields
        [CompilerGenerated]
        private string k__BackingField;

        // Properties
        public string Name
        {
            [CompilerGenerated]
            get
            {
                return this.k__BackingField;
            }
            [CompilerGenerated]
            set
            {
                this.k__BackingField = value;
            }
        }
    }

This is basically old school style of defining properties, only made easier syntactically. So the bottom line is that the auto-implemented properties will:

1. automatically creates a hidden field.
2. automatically creates a getter that returns the field.
3. automatically creates a setter that assigns the field.

References:
1. MSDN: Auto-Implemented Properties

Advertisements

Written by cavemansblog

March 25, 2011 at 11:38 am

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: