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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: