Create an Object and Set Its Properties with a Single Line of Code

There is a shortcut for both declaring an instance of a class and setting the initial value of all or some of its members. With a single line of code, you can instantiate an object and set a number of properties on that object. During runtime, the object is first created and then the properties are set in the order in which they appear in the initialization list. This feature is called object initializers.

Let’s look at an example. Suppose you have a class called Employee that has a number of properties such as FirstName, LastName, FullName, Title, and the like. Using object initialization, you can both create an instance of this class and set the initial values of some (or all) ...

Get Microsoft® Visual Studio® 2010 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.