#648 – Using an Object Initializer
August 14, 2012 6 Comments
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.
Pingback: #655 – Initializing Only Some Properties with An Object Initializer « 2,000 Things You Should Know About C#
Pingback: #656 – Nested Object Initializers « 2,000 Things You Should Know About C#
Pingback: #703 – Object Initializers Allow Setting Either Fields or Properties « 2,000 Things You Should Know About C#
Pingback: #833 – Some Examples of Anonymous Object Initializers | 2,000 Things You Should Know About C#
Pingback: #836 – Initializing a Generic List with an Object Initializer | 2,000 Things You Should Know About C#
Pingback: #837 – Object Initializers within Collection Initializers | 2,000 Things You Should Know About C#