3

This is a simple question really. I've been using the new type of constructors in .NET 3.5 (C#), but I would like to know what they're are called, if they've got a name at all :)

The constructor I'm talking about is this:

Customer c = new Customer()
{
    Name = "Bo"
};
3
  • 2
    Note that in this case you can omit the parens: new Customer { Name = "Bo" }; Nov 4, 2009 at 13:44
  • You should put four spaces before any code so it gets formatted properly as code. Did that for you. :) Nov 4, 2009 at 13:45
  • Alright, thanks a lot Martinho :) Nov 4, 2009 at 13:46

3 Answers 3

15

You're using the regular parameterless constructor but also the new feature which is called an Object Initializer.

2
  • Damn, even beat me to the linking :) Nov 4, 2009 at 13:44
  • @Richard Szalay: No I didn't, Martinho did. Good Job Martinho! Nov 4, 2009 at 13:45
8

As others have already noted, they are called Object Initializers.

However, they are not constructors, and you shouldn't go around referring to them as such.

Consider the following code:

public class TestHarness
{
    static void Main(string[] args)
    {
        Class1 class1 = new Class1();
        class1.Foo = "foo";

        Class2 class2 =
            new Class2
            {
                Foo = "foo"
            };
    }
}

public class Class1
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

public class Class2
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

Look at the IL generated for the Main method:

.method private hidebysig static void Main(string[] args) cil managed
{
    .maxstack 2
    .locals init (
        [0] class ClassLibrary1.Class1 class2,
        [1] class ClassLibrary1.Class2 class3,
        [2] class ClassLibrary1.Class2 class4)
    L_0000: nop 
    L_0001: newobj instance void ClassLibrary1.Class1::.ctor()
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: ldstr "foo"
    L_000d: callvirt instance void ClassLibrary1.Class1::set_Foo(string)
    L_0012: nop 
    L_0013: newobj instance void ClassLibrary1.Class2::.ctor()
    L_0018: stloc.2 
    L_0019: ldloc.2 
    L_001a: ldstr "foo"
    L_001f: callvirt instance void ClassLibrary1.Class2::set_Foo(string)
    L_0024: nop 
    L_0025: ldloc.2 
    L_0026: stloc.1 
    L_0027: ret 
}

You can see that the compiler has generated code which sets the Foo property for both class1 and class2. It did not generate a constructor which takes and sets Foo. A minor point, but it's best to understand the difference.

3

They are called Object Initializers. More info about them can be found here: http://weblogs.asp.net/dwahlin/archive/2007/09/09/c-3-0-features-object-initializers.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.