Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a parameter into an object in curly brackets during instantiation in C#

When you pass an variable into an object during instantiation, such as in

SomeObject newObject = new SomeObject() { SomeString = "String goes here" };

Will the variable SomeString be accessible in the constructor or will it be assigned afterwards? If I needed to use it in the constructor, would it work or would I need to pass it through as a parameter using

new SomeObject("String goes here");
like image 952
Jordan Wallwork Avatar asked May 30 '11 21:05

Jordan Wallwork


2 Answers

will the variable SomeString be accessible in the constructor, or will it be assigned afterwards?

It will be assigned afterwards.

SomeObject newObject = new SomeObject() { SomeString = "String goes here" };

is roughly equivalent/syntactic sugar to:

SomeObject temp = new SomeObject();
temp.SomeString = "String goes here";
SomeObject newObject = temp;
like image 65
Darin Dimitrov Avatar answered Nov 06 '22 02:11

Darin Dimitrov


It will be assigned afterwards in the first case. NOTE: This requires there to be a parameterless constructor, which will exist by default, unless you define a parameterized constructor. In that case you must define both constructors explicitly.

For more detail you can look at details on Object Initializers.

like image 21
Jason Down Avatar answered Nov 06 '22 02:11

Jason Down