New constructors in .NET 3.5

This is a simple question. I used a new type of constructors in .NET 3.5 (C #), but I would like to know what they are called if they have a name at all :)

The constructor I'm talking about is this:

Customer c = new Customer()
{
    Name = "Bo"
};
+3
source share
3 answers

You are using a regular constructor without parameters, as well as a new function called Object Initializer .

+15
source

As already noted, they are called Object Initializers.

However, they are not constructors , and you should not do with reference 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 
}

, , Foo 1 2. , Foo. , .

+8

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

+3
source

Source: https://habr.com/ru/post/1721879/


All Articles