In this lesson, we’re going to talk about Object Initializers. We have already seen how constructors can be used to set object properties with initial values and Object Initializers work in a somewhat similar way, allowing you to make your code much more compact and concise than it has been thus far.
Step 1: Create a New Project
For this lesson, create an ASP.NET project called “CS-ASP_047”, using where we left off in the previous lesson as the starting point.
Imagine that we didn’t have an overloaded version of the constructor for the Car class. How would we initialize these properties?:
The most obvious way would be to set the properties individually, right after instantiation:
Step 2: Using Object Initializers Instead of Constructors
Object Initializers allow you to set a given type’s properties all on one line, with more clarity, and less typing. To do this, you would use the same syntax when creating a new instance of the Car class, but after the opening and closing parentheses add an open angled bracket. Inside the brackets, you set the properties manually like so:
And then we can add the objects to a List the way we have seen before:
IntelliSense will even help you when using this method for setting the properties of a given type. Notice that as you type the angled bracket and press the space bar, IntelliSense shows you the following:
IntelliSense not only shows you the properties, but also their type, in this case an integer. This helps you, or even someone coming after you, to see exactly what properties this type has.
Step 3: Adding an Un-Named Object to a List
However, we can save keystrokes when adding a new object to a list by using an Object Initializer to create a new, un-named, object and pass it right in to the Add() method:
We don’t even need the object’s identifier, in this case, because the reference is being held by its position within the List and can be accessed as any list member, such as by iterating through it: