#704 – Using an Object Initializer with Any Constructor

One common pattern for using an object initializer to initalize select properties or fields of an object is to use the following syntax.

            Dog d = new Dog { Name = "Bowzer", Age = 2 };

When using this syntax, the default (parameterless) constructor for the class is called. After the object is constructed, the specified values are assigned to the appropriate properties.

You can also  construct the object using any custom constructor, followed by an object initializer.

For example, let’s say that the Dog class only has a single constructor, which takes two arguments to set the Name and Age properties.  You can then do the following:

            Dog d = new Dog("Bowzer", 2) { CollarSize = 12.4 };

The constructor is called, setting Name and Age. After the object is constructed, the CollarSize property is initialized to contain a value of 12.4.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: