Reputation: 4523
Given the class
public class B
{
public bool flag = false;
public B()
{
}
}
When I initialize it with the line
var jjj = new B(){flag = true};
If I put a breakpoint inside the constructor B(), flag is false. I expected it to be true because I called "flag = true" when I initialized it.
What am I doing wrong?
Upvotes: 3
Views: 80
Reputation: 391276
That syntax is equivalent to this:
var temp = new B();
temp.flag = true;
var jjj = temp;
So in the constructor, flag
is still false
, and is set from the outside afterwards.
This is not special syntax to inject more code into a constructor, it all happens afterwards.
Note that it is not equivalent to this:
var jjj = new B();
jjj.flag = true;
While in this case it might not matter, but if jjj
was a field or a property instead, you would potentially expose an object you're not done configuring early. As such, a temporary variable is constructed to hold your object while it is being initialized, and only afterwards is the object stored into its intended destination.
Here is some more information about object initializers:
Addendum: As mentiond by @Tim in the comments, if you really want a constructor that initialized flag
you should add an overloaded constructor with the right parameter:
public B(bool flagValue)
{
flag = flagValue;
}
Upvotes: 9
Reputation: 6368
Create a constructor like :
public class B
{
public bool flag = false;
public B()
{
}
public B(bool Flag)
{
flag = Flag;
}
}
Then try to call it like :
var jjj = new B(true);
Upvotes: 1