Thursday, September 4, 2014

C# Auto-Implemented Properties

Intro

Ferrari; beautiful sunset; big stack of cash; a hilarious comedy...what do all these things have in common? They're all nearly as cool as c# Auto-Implemented Properties. Yes that's right folks, coding is now cool just like me (ahem). What's an auto-implemented property you ask? Well for starters, thanks for asking. An auto-implemented property is one more thing you can take advantage of to save you some keyboard strokes. Yep that's it folks, less keyboard strokes! (the crowd goes wild). Let's see how auto-implemented properties accomplish such a monumental feat here in the next section.

Example

Here is a very simple example of an auto-implemented property.

    public class Aip
    {
        public string Description { get; set; }
    }


I'm sure you're all used to seeing properties in classes by now. What you might not have seen though is a property that just has "get;" or "set;" within the property declaration, which is an auto-implemented property. Believe it or not, this is a functional class that compiles. You can even get and set the property Description with code like this:

        protected void Page_Load(object sender, EventArgs e)
        {
            var aip = new Aip();
            aip.Description = "hi, i'm tom!";
            Response.Write(aip.Description);
        }


Here we create an object of type Aip, set the description, then read the description. It works just like a normal class with a normal property, only you didn't have to create a (usually private) field behind the property. C# did that for you behind the scenes!

Why?

I already covered this fool! But hey, it's because you can save yourself some time. The above class declaration for Aip is easier than what you would normally do prior to auto-implemented properties:

    public class Aip
    {
        private string mDescription;

        public string Description
        {
            get
            {
                return mDescription;
            }
            set
            {
                mDescription = value;
            }
        }
    }


Yeah it's not a big difference, but it does add up. If you've got a lot of properties to define in an object, give it a whirl! You'll appreciate having a couple extra minutes of your time to do other things.

Limitations

One obvious limitation is that you can't do other things in the getter and setter. They're auto-implemented after all, not manual! So if you need to put any extra logic in your setter or getter, you'll need to implement the property fully yourself.

Limitation 2: Auto-implemented properties must have both a getter and a setter. You can however put the private keyword in front of either the getter or setter to hide them from prying eyes if you really need to.

What's Next

Try it out! I'm sure you've got a project coming up where you can use this.

Resources

Auto-Implemented Properties

No comments:

Post a Comment