#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.

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