Object Initializers

Any accessible fields or properties of an object can be set via an object initializer directly after construction.

public class Bunny
{
	public string Name;
	public bool LikesCarrots;
	public bool LikesHumans;

	public Bunny () {}
	public Bunny (string n) { Name = n; }
}

// Note parameterless constructors can omit empty parentheses
Bunny b1 = new Bunny { Name="Bo", LikesCarrots=true, LikesHumans=false };
Bunny b2 = new Bunny ("Bo") { LikesCarrots=true, LikesHumans=false };

Is equivalent to:

Bunny temp1 = new Bunny(); // temp1 is a compiler-generated name
temp1.Name = "Bo";
temp1.LikesCarrots = true;
temp1.LikesHumans = false;
Bunny b1 = temp1;


Bunny temp2 = new Bunny ("Bo");
temp2.LikesCarrots = true;
temp2.LikesHumans = false;
Bunny b2 = temp2;

Object Initializers Versus Optional Parameters

Instead of using object initializers, we could make Bunny’s constructor accept
optional parameters.

public Bunny (string name,
bool likesCarrots = false,
bool likesHumans = false)
{
Name = name;
LikesCarrots = likesCarrots;
LikesHumans = likesHumans;
}

This would allow us to construct a Bunny as follows:

Bunny b1 = new Bunny (name: "Bo",likesCarrots: true);

Advantage

  1. Can make fields or properties readonly./li>
  2. Making fields or properties read-only is good practice when there’s no reason to change throughout the life of the object.

Disadvantage
Each optional parameter value is baked into the calling site.
The compiler will translate into:

Bunny b1 = new Bunny ("Bo", true, false);

This can be problematic if we instantiate the Bunny class from another assembly and
later modify Bunny by adding another optional parameter—such as likesCats.

Leave a Reply

Your email address will not be published. Required fields are marked *