Monday, December 04, 2006 4:17 AM bart

C# 3.0 Feature Focus - Part 2 - Object Initializers

 

Introduction

In this C# 3.0 Feature Focus Week we'll focus on the new language features that will be part of C# 3.0 "Orcas". As you already might know, the major innovation on Orcas is the LINQ (Language Integrated Query) technology that will make data queries a first class citizen of the language (C# 3.0 and VB 9.0). In order to unlock this potential, a set of language features were added to the language that all work in concert to enable LINQ stuff. However, all of those individual features prove to be useful in isolation as well. Later, we'll focus on LINQ itself.

 

Object Initializers

So, you're tired of having to set a bunch of properties one by one after you've created an object, like this?

using System;

class Oini
{
   public static void Main()
   {
      Customer c = new Customer();
      c.Name = "Bart"
;
      c.City = "Ghent";
      c.Age  = 23;

   }
}

Wouldn't it be nice to do this in just one line of code? I agree, it would be even nicer if the Customer class had a constructor that could help us, but you don't have that level of control all the time and maybe you just want to set some properties or you're out of luck with the constructors available. Therefore, C# 3.0 allows you to do this:

using System;

class Oini
{
   public static void Main()
   {
      Customer c = new Customer() { Name = "Bart", City = "Ghent", Age = 23 };
   }
}

You can also omit the () of the constructor call. All of this magic assumes you have some Customer type with public property setters and a default constructor. The IL produced looks as follows:

.method public hidebysig static void Main() cil managed
{
   .entrypoint
   .locals init (class Customer V_0,
            class Customer V_1)
   IL_0000: nop
   IL_0001: nop
   IL_0002: newobj instance void Customer::.ctor()
   IL_0007: stloc.1
   IL_0008: ldloc.1
   IL_0009: ldstr "Bart"
   IL_000e: callvirt instance void Customer::set_Name(string)
   IL_0013: nop
   IL_0014: ldloc.1
   IL_0015: ldstr "Ghent"
   IL_001a: callvirt instance void Customer::set_City(string)
   IL_001f: nop
   IL_0020: ldloc.1
   IL_0021: ldc.i4.s 23
   IL_0023: callvirt instance void Customer::set_Age(int32)
   IL_0028: nop
   IL_0029: ldloc.1
   IL_002a: nop
   IL_002b: stloc.0
   IL_002c: ret
} // end of method Oini::Main

In a similar way you can initialize an object of a type that has public fields on it. Assuming the Name, Age and City properties are now replaced by public fields, the IL would look like this (rather predictable):

.method public hidebysig static void Main() cil managed
{
   .entrypoint
   .locals init (class Customer V_0,
            class Customer V_1)
   IL_0000: nop
   IL_0001: nop
   IL_0002: newobj instance void Customer::.ctor()
   IL_0007: stloc.1
   IL_0008: ldloc.1
   IL_0009: ldstr "Bart"
   IL_000e: stfld string Customer::Name
   IL_0013: ldloc.1
   IL_0014: ldstr "Ghent"
   IL_0019: stfld string Customer::City
   IL_001e: ldloc.1
   IL_001f: ldc.i4.s 23
   IL_0021: stfld int32 Customer::Age
   IL_0026: ldloc.1
   IL_0027: nop
   IL_0028: stloc.0
   IL_0029: ret
} // end of method Oini::Main

In case you do have a constructor at hand but it hasn't enough flexibility, one can combine both approaches:

using System;

class Oini
{
   public static void Main()
   {
      Customer c = new Customer("Bart") { City = "Ghent", Age = 23 };
   }
}

which produces this piece of IL:

.method public hidebysig static void Main() cil managed
{
   .entrypoint
   .locals init (class Customer V_0,
            class Customer V_1)
   IL_0000: nop
   IL_0001: nop
   IL_0002: ldstr "Bart"
   IL_0007: newobj instance void Customer::.ctor(string)
   IL_000c: stloc.1
   IL_000d: ldloc.1
   IL_000e: ldstr "Ghent"
   IL_0013: callvirt instance void Customer::set_City(string)
   IL_0018: nop
   IL_0019: ldloc.1
   IL_001a: ldc.i4.s 23
   IL_001c: callvirt instance void Customer::set_Age(int32)
   IL_0021: nop
   IL_0022: ldloc.1
   IL_0023: nop
   IL_0024: stloc.0
   IL_0025: ret
} // end of method Oini::Main

Another nice thing about this is that you don't have to specify the property's (or field's) name in case the compiler can find it on its own, like this:

using System;

class Oini
{
   public static void Main()
   {
      Customer c1 = new Customer() { Name = "Bart", City = "Ghent", Age = 23 };

      Customer c2 = new Customer() { Name = "John", c1.City, c1.Age };
   }
}

In the case of Customer c2, the compiler observes a City property is used in the object initializer, so it checks whether there's a public property (or field) called City available that can be set. The same happens for the Age property.

Also think about the convenience when doing "nesting" to construct very complex objects:

using System;

class Oini
{
   public static void Main()
   {
      Customer c = new Customer {
         Name = "Bart",
         Age = 23,
         Address = new Address {
            Street = "Andersstreet",
            Number = 60,
            PostalCode = 9000,
            City = "Ghent"
        
}
      };

   }
}

Without this feature you'd either end up with a temporary variable to hold the Address object or with a bunch of calls like c.Address.* = <something>.

To conclude, I'd say: just use it! A quiz would be too easy in this case :-).

kick it on DotNetKicks.com

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under:

Comments

# New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers

Thursday, March 08, 2007 11:02 PM by ScottGu's Blog

Last week we shipped the March CTP of our Visual Studio and .NET Framework "Orcas" release. It is available

# New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers

Thursday, March 08, 2007 11:31 PM by BusinessRx Reading List

Last week we shipped the March CTP of our Visual Studio and .NET Framework "Orcas" release. It is available

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Saturday, March 10, 2007 6:12 PM by Joycode@Ab110.com

【原文地址】 New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Saturday, March 10, 2007 6:50 PM by Athrun

【原文地址】NewC#

# New C#

Saturday, March 10, 2007 7:26 PM by Adrian.

Scott Guthrie介绍的C# 3.0中的语言新特性

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Sunday, March 18, 2007 8:32 PM by shoutor

上个星期,我们发布了我们的Visual Studio和.NET框架Orcas版三月份的CTP,这是个谁都可以下的免费下载,同时提供VPC镜像(允许你在一个虚拟机里运行它)以及单独的安装文件(注:如果你在运行Vista的话,你要确认你只使用VPC版本)。你可以在这里下载。

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Tuesday, March 20, 2007 4:22 AM by 清清月儿

除了那些框架和工具类的精彩新特性外,我认为开发人员(包括所有的.NET应用类型的开发人员)会非常喜爱Orcas的一件事情是,VB和C#将包含一些新语言特性和改进。这些语言改动将以既微妙又深刻的方式改进我们的开发体验,势将改进效率,减小我们需要键入的代码量。

# Hungry for "Orcas"? Try the March CTP!

Thursday, March 22, 2007 6:21 PM by Robert Burke's Weblog

"Orcas" is the codename for the next release of Visual Studio, which will allow you to develop applications

# Hungry for "Orcas"? Try the March CTP!

Thursday, March 22, 2007 7:32 PM by RSS It All

&quot;Orcas&quot; is the codename for the next release of Visual Studio, which will allow you to develop

# Nuevas caracter??sticas de la nueva versi??n de C# Orcas &laquo; Thinking in .NET

# New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers

Thursday, March 29, 2007 4:20 AM by ASP.NET

Last week we shipped the March CTP of our Visual Studio and .NET Framework "Orcas" release. It is available

# The IQueryable tales - LINQ to LDAP - Part 0

Thursday, April 05, 2007 7:04 PM by B# .NET Blog

Here we are again for some cool LINQ stuff. In the past I've been blogging on C# 3.0 language innovation

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Saturday, April 28, 2007 5:31 PM by 清风涤尘

.net c# 改进 语言 特性 .net3.0新特新

# Lo nuevo de C# 3.0 (2 de n): Inicializadores de objetos

Monday, July 16, 2007 8:48 PM by .NET a 2.860 m de altura

En C# 2.0 cuando queremos instanciar un objeto e inicializar sus propiedades, debemos recurrir a c&oacute;digo

# C#3.0 object initializer

Friday, August 03, 2007 1:37 AM by kangnoz

延续上一篇automatic properties的内容,在C#3.0中我们可以用这种syntax来初始化一个对象

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Tuesday, August 21, 2007 6:53 PM by BoardPung

Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Wednesday, August 22, 2007 4:58 AM by 瑞克

【原文地址】NewC#

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Wednesday, August 22, 2007 4:59 AM by 瑞克

【原文地址】NewC#

# Neues .NET 3.5 Feature: Object Initializers

Thursday, November 15, 2007 1:57 PM by Jürgen Gutsch

Die Nummer drei die ich hier vorstellen möchte, ist ebenfalls für Leute wie mich das absolute Highlight

# Object Initializers

Monday, November 19, 2007 8:58 AM by Gyun's Blog

Object Initializers

# Visual Studio 2008 - &quot;Ah&quot; #1 - Automatic Properties and Object Initializers &laquo; Alex Duggleby&#8217;s Palace of Words

Pingback from  Visual Studio 2008 - &quot;Ah&quot; #1 - Automatic Properties and Object Initializers &laquo; Alex Duggleby&#8217;s Palace of Words

# C# 3.0 Object Initializers Revisited

Thursday, November 22, 2007 1:14 PM by B# .NET Blog

A while ago I posted about this new C# 3.0 feature . Although the IL code (aargh, yet another of these

# C# 3.0 Object Initializers Revisited

Thursday, November 22, 2007 1:32 PM by Elan Hasson's Favorite Blogs

A while ago I posted about this new C# 3.0 feature . Although the IL code (aargh, yet another of these

# New C# 3.0 -

Tuesday, November 27, 2007 2:12 AM by Vu Nguyen's Blog

New C# 3.0 -

# C# 3.0 Object Initializers Revisited

Friday, December 21, 2007 7:44 AM by Developer Blogs

A while ago I posted about this new C# 3.0 feature . Although the IL code (aargh, yet another of these

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Friday, January 04, 2008 12:33 AM by 幸福

NewC#

# .NET??????Orcas?????????,????????????????????????????????????????????????????????? | Richie's Blog

Pingback from  .NET??????Orcas?????????,????????????????????????????????????????????????????????? | Richie's Blog

# C# 3.0 Feature Focus – Link Collection

Saturday, August 09, 2008 7:13 AM by B# .NET Blog

Collecting a few of my posts for easy quick reference: C# 3.0 Feature Focus - Part 1 - Local Type Inference

# New C# &#8220;Orcas&#8221; Language Features: Automatic Properties, Object Initializers, and Collection Initializers &laquo; using &#8230;

Pingback from  New C# &#8220;Orcas&#8221; Language Features: Automatic Properties, Object Initializers, and Collection Initializers  &laquo; using &#8230;

# C#的新特性:自动属性,对象初始化器,和集合初始化器(转载)

Saturday, December 27, 2008 7:17 AM by 小戚园地

【原文地址】NewC#

# C#语言的新特性:对象初始化器(Object Initializers)

Tuesday, August 11, 2009 8:31 PM by 袁磊

C#语言的新特性:对象初始化器(ObjectInitializers).NET框架中的类型非常依赖于属性的使用。当生成对象实例和使用新的类型时,写出象下面这样的编码是非常常见的情形:...

# Using LINQ : Automatic Properties, Object Initializer and Collection Initializers &laquo; T. Nayak

Pingback from  Using LINQ : Automatic Properties, Object Initializer and Collection Initializers &laquo; T. Nayak

# New C# &#8220;Orcas&#8221; Language Features: Automatic Properties, Object Initializers, and Collection Initializers | kanhyathakur

Pingback from  New C# &#8220;Orcas&#8221; Language Features: Automatic Properties, Object Initializers, and Collection Initializers | kanhyathakur