DCSIMG
C#3.0 Feature: Object Initializers, not as simple as it looks like - Yochay Kiriaty

Yochay Kiriaty

I find your lack of faith disturbing

C#3.0 Feature: Object Initializers, not as simple as it looks like

During my C# 3.0 deep dive in the Developer Academy II, I presented a new syntactic sugar feature in C# 3.0 called Object Initializers which enables you to init object members using a new (and somewhat odd) syntax that looks like an inlining of values directly to the object members.

Given a Customer object with three string fields, City, ContactName, and CustomerID with only default constructor (C# 3.0 code using Automatic Implemented Properties)

    public class Customer

    {

        public string CustomerID { get; set; }

        public string ContactName { get; set; }

        public string City { get; set; }

    }

 

In C# 3.0, I can now write this line of code:

   // C#3.0 Feature:  Object Initializers

   Customer customer = new Customer()

   {

        City = "Airport City",

        ContactName = "ABC",

        CustomerID = "1"

   };


These lines of code create a new Customer object with the values set to his corresponding members. The feature is really becoming useful when a given object has more than just three member fields. Consider having a lot of members in an object, and you would like to initialize any number of these members in any combination, and in a single line of code - similar to calling different constructor. However you don’t want to overwrite the constructor with all the different permutation of the member field (remember the .NET don’t support default values in the constructor). Therefore using Object Initializers syntactic sugar is a very effective programming. This allows you to reduce the total amount of code you write – no need to create all those overwriting constructors, and makes you code more readable and intuitive. Like everything in C# 3.0, this is really a simple compiler trick, which means it is nothing more than a simple syntactic sugar.

 However with that said, there is one point that we need to address and spent few minutes contemplating on. Given the Customer class and the Object Initializer statement defined above, the compiler generates the following code:

 

clip_image002

The compilers generates a “temporary” (not really temporary) Customer object called customer2 , init its property fields with the corresponding values, and only then assign the temporary customer2 object reference to our original Customer object.

From a quick glance, this may look redundant, uncalled for, very old coding style, not preferment and in general looks like a bug service pack 1 will need to fix. But actually, this is not a bug, it is a feature. This feature is called Atomic Assignment and it is an important feature to protect us stupid programmers from making too many stupid mistakes.

To explain who does Atomic Assignment works, consider the general case here.  What if you write the following code:

class Customer

{

     //dont do that at home

    public byte Age;

    public bool Cool;

    public string City;

    public Customer ReferredBy;

}

 

class Program

{

    static void Main()

    {

        Customer customer = new Customer

        {

           Age = 0x1a,

           Cool = true,

           City = "Airport City",

           ReferredBy = null

        };

        customer = new Customer

        {

           Age = 0x33,

           Cool = false,

           City = "Tugboat City",

           ReferredBy = customer

       };

    }

}

In this case, two separate instances will be constructed, each of which is stored in the customer variable.  However, a property initializer for the second instance refers to the first instance.  If temporary objects were not used, the ReferredBy = customer initializer would point the second instance at itself, instead of at the first instance.

Situations like this are the reason it‘s usually preferable to generate the verifiably correct code and let the JIT optimize the resulting MSIL if possible.

 

Published Monday, December 10, 2007 4:23 PM by Mr.J

Comments

# re: C#3.0 Feature: Object Initializers, not as simple as it looks like@ Saturday, December 22, 2007 5:41 PM

I'm wondering - how did you come up with this specific scenario?

by Anon

# re: C#3.0 Feature: Object Initializers, not as simple as it looks like@ Thursday, February 07, 2008 10:56 AM

יוחאי שלום,

פגשתי אותך אתמול בכנס VBGroup, והיית רוצה לשאול אותך מספר שאלות:

1. שמעתי שיש מעיין יום עיון אודות AJAX.NET ורציתי לדעת פרטים.

2.שמעתי שיש קבוצות נוספות בנושא Security למפתחים וכן קהילת C#, ורציתי לדעת כיצד נרשמים ומה מועדי המפגשים.

3.האם ישנם קבוצות דיון בתחום השיווק (כלשהוא), כדוגמת מכירות, ניהול שיווק, פריסל וכו'?

אשמח אם תוכל לענות לכתובת המייל המצורפת.

בתודה מראש

רובי שרון

SRL

RUVIS@SRL.CO.IL

by רובי שרון

# re: C#3.0 Feature: Object Initializers, not as simple as it looks like@ Monday, May 18, 2009 9:58 AM

www.message_actrorelv.com

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: