Auto-Implemented Properties & Object Initializers - Hilton Giesenow's Jumbled Mind

Hilton Giesenow's Jumbled Mind

the madness that is...

News

This is my little spot in cyberspace where you will find a collection of random (but mostly software-related) thoughts and ideas that are frightening in their shining brilliance (or something like that ;->).
 
Please enjoy your stay and feel free to Contact Me.
 
Microsoft MVP

.Net Links

BlogRoll

Misc. Links

Syndication

Auto-Implemented Properties & Object Initializers

Auto-Implemented Properties

I'm working on a C# 3.0 project at the moment and getting to use all the new toys and features and they really are quite fun so far. Working with them has given me a chance to think about them more and I've been giving some thought to Auto-Implemented Properties (or just "auto-properties" as they're sometimes affectionately called). The syntax, in case you haven't seem them, is basically:

public int MyProperty { get; set; }

Under the covers, the C# compiler will actually generate a private field for you, which is pretty cool. You can create read-only properties very easily using this feature too, like so:

public int MyProperty { get; private set; }

Write-only properties are not supported, but attributes are (despite what some of the documentation says - I think it may have not been supported in early beta releases but that this changed. Atif Aziz added a comment to this affect on the MSDN page for auto-properties, and I've been using them quite successfully in WCF with the DataMember attribute). Scott Guthrie of course discusses the feature further on a post on his blog.

However, what I've been giving some thought to is - what is the difference between an auto-property, such as:

public int MyProperty { get; set; }

and just a public field, such as:

public int MyProperty;

Effectively, from the class developer's perspective, they're much the same thing. The first might actually be quicker to type because of the 'prop' code snippet, but essentially they're providing the same thing. Trey Nash gets into it a bit here, and he comments that it affects the encapsulation, which is true, but I think the main point of using an auto-property is that, once a client is bound to your property, they won't be affected if you decide to change it to using a backing private field, for instance to add an event call, set another property (perhaps a 'dirty' flag), or similar. Client code that uses your property would, in these instances, not need a recompile, whereas they would if a public field became a property.

Object Initializers

One of the other new features I've been playing with is Object Initializers, which basically let you set any properties on an object when you initialize it, but without needing explicit constructors. This only works for non-read-only properties (makes sense ;->), and works as follows. For the following class:

    public class Customer
    {

        public string FirstName { get; set; }

        public string LastName { get; set; }
    }

You could write code to use this class and set the properties without needing a specific constructor, as follows:

Customer customer = new Customer { FirstName = "Hilton", LastName = "Giesenow" };

And you can set or not set any of the non-readonly properties in this way. However, what might not be obvious is that you can still create specific explicit constructors and combine the two. You might want to initialize a base class or do some other work which may make a constructor worthwhile. Alternatively, let's say you want to set one of the (auto-)properties to be readonly (as we learnt about a few paragraphs ago), as follows:

    public class Customer
    {
        public Customer(string newLastName)
        {
            this.LastName = LastName;
        }

        public string FirstName { get; set; }

        public string LastName { get; private set; }
    }

Now the only way to set the LastName property is to use the new constructor, as follows:

Customer customer = new Customer("Giesenow") { FirstName = "Hilton" };

Where this gets tricky is that, in this example you can now no longer use the original call with no constructor, because no default constructor now exists for the class. To be able to just set the FirstName property, add a regular old default constructor, as follows:

    public class Customer
    {
        public Customer()
        {

        }
        public Customer(string newLastName)
        {
            this.LastName = LastName;
        }

        public string FirstName { get; set; }

        public string LastName { get; private set; }
    }
and you can once again do the following:

Customer customer = new Customer { FirstName = "Hilton" };

Enjoy :-)

Comments

Jessy Houle said:

To your earlier question, "What is the difference" when referring to a public field verses a property, (either auto-property or regular) would be binding.  I have not tested it yet, but I can only imagine that auto-properties allow binding, and conversely, I do not think that public fields are bindable.

Thank you for your posts.  I enjoy.

-Jessy Houle

# March 19, 2008 11:04 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: