Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between class initializers in C#? [duplicate]

Possible Duplicate:
Why are C# 3.0 object initializer constructor parentheses optional?

What is the difference between instatiating an object by using

classInstance = new Class() { prop1 = "", prop2 = "" };

and

classInstance = new Class { prop1 = "", prop2 = "" };

like image 430
kavun Avatar asked Jun 10 '11 17:06

kavun


People also ask

What are initializers in C?

Initializer. In C/C99/C++, an initializer is an optional part of a declarator. It consists of the '=' character followed by an expression or a comma-separated list of expressions placed in curly brackets (braces).

What is the difference between initialization and assignment in C?

What is the difference between initialization and assignment? Initialization gives a variable an initial value at the point when it is created. Assignment gives a variable a value at some point after the variable is created.

What is the use of initializer?

An initializer is an optional part of a data declaration that specifies an initial value of a data object. The initializers that are legal for a particular declaration depend on the type and storage class of the object to be initialized.

What are the advantages of initializer list?

The most common benefit of doing this is improved performance. If the expression whatever is the same type as member variable x_, the result of the whatever expression is constructed directly inside x_ — the compiler does not make a separate copy of the object.


1 Answers

Short answer: Nothing. The () can be used if you want to pass in some constructor args but in your case since you don't have any, you can skip ().

For eg. () is useful here.

  Foo foo = new Foo(someBar){Prop1 = "value1", Prop2 = value2};

but if you are trying to call the parameter-less constructor, it's optional

  Foo foo = new Foo {Prop1 = "value1", Prop2 = value2};
like image 164
Bala R Avatar answered Oct 08 '22 06:10

Bala R