Object initialization
Learn to initialize objects concisely with object initializer syntax.
Object initializer
Instead of assigning properties one by one after creating an object, you can use an object initializer to do it in one line: new Book { Title = "Hamlet", Pages = 342 }.
Here new Book() first calls the constructor, then each assignment inside the braces is applied to a property. Multiple properties are separated by commas. The code becomes shorter and more readable. The same syntax works for collections too.
Collection initializer
Similar syntax works for collections. new List<string> { "apple", "pear", "cherry" } creates a new list and adds three items.
Each item inside the braces is passed to the collection's Add method. This is much shorter than writing multiple items.Add(...) calls. You can also combine object and collection initializers: new Cart { Items = new List<string> { "book" } }.
Exercise Create a Book with an object initializer
The Book class below is given. Inside Main use an object initializer to create an instance with Title = "Hamlet" and Pages = 342, then print Title.
Show example solution
Write Book b = new Book { Title = "Hamlet", Pages = 342 };. Then add Console.WriteLine(b.Title);.
Example solution:
using System;
class Book
{
public string Title { get; set; }
public int Pages { get; set; }
}
class Program
{
static void Main()
{
Book b = new Book { Title = "Hamlet", Pages = 342 };
Console.WriteLine(b.Title);
}
}
Test yourself
-
Match each initializer part to its role
- new Book
- Creates instance
- { Title = "x" }
- Sets a property
- =
- Binds a value
- }
- Closes the initializer
-
Which is the object initializer syntax?
- new Book().Title = "x";
- new Book(Title="x")
- new Book { Title = "x" }
- new Book: Title = "x"
Show answer
new Book { Title = "x" } — Correct. new Type { Property = value } is the initializer syntax.
-
Complete the object initializer
Book b = new Book { Title = ____ };Show answer
Book b = new Book { Title = "Hamlet" };