#648 – Using an Object Initializer

You typically initialize the data members of an object by invoking one of the object’s constructors and passing it any information that it requires.  For example:

Dog kirby = new Dog("Kirby", 14);

If a parameterless constructor exists for the class, you can alternatively create the object without invoking a constructor, using the object initializer syntax shown below.

Dog kirby = new Dog { Name="Kirby", Age=14 };

This is functionally equivalent to:

Dog kirby = new Dog();
kirby.Name = "Kirby";
kirby.Age = 14;

If a parameterless constructor does not exist for the class, you can still use the object initializer syntax, but only after explicitly invoking one of the constructors.

Advertisement

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

6 Responses to #648 – Using an Object Initializer

  1. Pingback: #655 – Initializing Only Some Properties with An Object Initializer « 2,000 Things You Should Know About C#

  2. Pingback: #656 – Nested Object Initializers « 2,000 Things You Should Know About C#

  3. Pingback: #703 – Object Initializers Allow Setting Either Fields or Properties « 2,000 Things You Should Know About C#

  4. Pingback: #833 – Some Examples of Anonymous Object Initializers | 2,000 Things You Should Know About C#

  5. Pingback: #836 – Initializing a Generic List with an Object Initializer | 2,000 Things You Should Know About C#

  6. Pingback: #837 – Object Initializers within Collection Initializers | 2,000 Things You Should Know About C#

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: