#656 – Nested Object Initializers

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 }
            };

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

Leave a comment