#656 – Nested Object Initializers
August 24, 2012 Leave a comment
When using an object initializer to initialize the contents of an object, you can nest an inner object initializer to initialize an object that is referenced by a property of the outer object.
Assume that we have the following two classes:
public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int BirthYear { get; set; } } public class Movie { public string Title { get; set; } public int Year { get; set; } public Person Director { get; set; } public Person LeadActor { get; set; } }
We might then initialize a Movie object as follows:
Movie aMovie = new Movie { Title = "Psycho", Year = 1960, Director = new Person { FirstName = "Alfred", LastName = "Hitchcock", BirthYear = 1899 }, LeadActor = new Person { FirstName = "Anthony", LastName = "Perkins", BirthYear = 1932 } };