2 minute read

The other day I was doing my usual reading and came across some really cool information on Dan Wahlin’s blog about what we can expect in C# 3.0. Even though I disagree with some of the specs of C# 3.0, there are some really cool features worth noting in C# 3.0 like object initializers.

“C# 3.0 is just around the corner so I thought I’d start writing about a few of the features that it exposes and provide quick and concise examples of how they can be used. Many of the new features rely on the compiler to generate code that you would have had to write in the past. This can result in significantly less code compared to C# 2.0 syntax in many cases. Here’s a list of some of the key features available in C# 3.0:* Object Initializers

  • Anonymous Types
  • Automatic Properties
  • Extension Methods
  • Lambda Expressions
  • LINQ
  • Collection Initializers

In this post I’ll discuss the fundamentals of object initializers in C# 3.0. To get started, let’s look at the standard way of initializing an object with data in C# 2.0 using constructors. The following example creates a Person object and passes three values to its constructor.

Person p = new Person("John", "Doe", "602-123-1234");

As mentioned, C# 3.0 now supports the concept of “object initializers” which means you can easily assign data to specific properties in a type with having to create an explicit constructor (you can of course still create constructors as well). The standard C# { and } brackets are used to create object initializers.

Here’s an example of using an object initializer to assign property data to a Person type. It’s nice because doing the same thing without using a constructor in C# 2.0 would have resulted in around 5 lines of code which is too many for something simple like property value assignments.

Person p = new Person() {FirstName="John",LastName="Doe",Phone="602-123-1234",City="Phoenix"};

If the Person type defines a sub object as a property you can even use object initializers to create the sub object. Here’s an example of defining an Address object:

Person p = new Person()
{
    FirstName = "John",
    LastName = "Doe",
    Address = new Address()
    {
        Street = "1234 St.",
        City = "Phoenix"
    }
};

Read more here.

Join the mailing list

Get notified of new posts and related content to your inbox. I will never sell you anything and I will NEVER sell your email address.