简体   繁体   中英

Using () or {} when instantiating class in C#

Is there any difference in the initialization for x1 and x2?

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var x1 = new C { };

            var x2 = new C ();

        }
    }

    public class C
    {
        public int A; 
    }
}

In your example, there's no difference. Both are calling the default constructor and not passing in any values. The { } is the object initializer notation which allows you to set values on public properties that aren't passed in through the constructor.

Ex. With the following class, PropertyA is passed in through the constructor and PropertyA, PropertyB, PropertyC are settable on the object.

class TestClass
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
    public string PropertyC { get; set; }

    public TestClass(string propertyA)
    {
        propertyA = propertyA;
    }
}

If you needed set all values you could do this

var test1 = new TestClass("A");
test1.PropertyB = "B";
test1.PropertyC = "C";

Or the equivalent using the object initializer format would be

var test2 = new TestClass("A") {PropertyB = "B", PropertyC = "C"};

No, they compile to the same code

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       14 (0xe)
  .maxstack  1
  .locals init ([0] class ConsoleApplication2.C x1,
           [1] class ConsoleApplication2.C x2)
  IL_0000:  nop
  IL_0001:  newobj     instance void ConsoleApplication2.C::.ctor()
  IL_0006:  stloc.0
  IL_0007:  newobj     instance void ConsoleApplication2.C::.ctor()
  IL_000c:  stloc.1
  IL_000d:  ret
} // end of method Program::Main

however x2 is the standard coding style when dealing with a parameterless constructor and not initializing any values using the object initializer.

The curly bracket {} is used for object or collection initialization:

new C() { Property1 = "Value", Property2 = "etc..." };

It should be noted that here the () can be omitted, as it is the default constructor. Therefore, new C{} is basically new C() {} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM