#655 – Initializing Only Some Properties with An Object Initializer

Using an object initializer, you can initialize an object by specifying values for its public properties, as long as the object’s type defines a parameterless constructor.

Movie aMovie = new Movie { Title = "Life Is Beautiful", Year = 1997, Director = "Roberto Benigni" };

Using this syntax, you can initialize any subset of the objects properties that you like. Any properties not initialized will take on default values.

            Movie movie = new Movie { Title = "Fight Club", Year = 1999 };
            Movie movie2 = new Movie { Year = 1972, Director = "Francis Ford Coppola" };
            Movie movie3 = new Movie { Title = "Taxi Driver" };


You could even use an empty object initializer, which would be equivalent to invoking the parameterless constructor directly.

            Movie movie4 = new Movie { };
            Movie movie5 = new Movie();

Advertisements

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

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: