Object Initializers and Automatic Properties

One of the great ways to learn about all the nifty C# features is to google for new features by version (eg. C# 2.0, C# 3.0, …)

Two great features that shipped in C# 3.0 are: Object Initializers, and Automatic (Automagic?) Properties. Let’s cover the “business case,” first, from the perspective of developers as the customer.

Automatic Properties

There’s a pretty standard paradigm for adding properties; you add an instance variable called _property, and a public getter and setter that operate on it, something like:

class Person {
private int _age = 0;
public int Age {
get { return this._age; }
set { this._age = value; }

This is a pretty standard paradigm for getters and setters. As of .NET 3.0, you can abbreviate this code (using automatic properties) to:

class Person {
public int Age { get; set; }

It looks like an interface — but if you decompile the resulting code (or inspect the CIL), you’ll see that it creates the requisite member variable and mimics the code we wrote in the first sample.

Awesome! One caveat is that you can’t have read-only properties like this; it’s meant for getters and setters. The other caveat is that you cannot access _age, since it technically doesn’t exist at compile-time. This is good, because making your internal code use external interfaces means more robust and less fragile code — it depends on the contract, not the implementation.

Object Initializers

Let’s assume our Person object has a Name, Age, and Gender. It’s pretty common to see code like this:

Person p = new Person();
p.Name = "Jon";
p.Age = 32;
p.Gender = "M";

Or, if you utilize optional parameters and default values (new in C# 4.0), you might have something like:

Person p = new Person("Jon", 32, "M");

Object Initializers allow you to specify parameters by using the usual constructor syntax, followed by curly-braces, like so:

Person p = new Person() { Name="Jon", Age=32, Gender="M" }

And this is equivalent to the code that sets the properties manually — just decompile or inspect the CIL and see for yourself!

That concludes two small, but useful syntactic sugar-coating in .NET 3.0.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Silverlight, Web, Wndows Forms and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *