#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();

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

Leave a comment