Object initializers

Syntax

  • SomeClass sc = new SomeClass { Property1 = value1, Property2 = value2, ... };
  • SomeClass sc = new SomeClass(param1, param2, ...) { Property1 = value1, Property2 = value2, ... }

Remarks

The constructor parentheses can only be omitted if the type being instantiated has a default (parameterless) constructor available.

Simple usage

Object initializers are handy when you need to create an object and set a couple of properties right away, but the available constructors are not sufficient. Say you have a class

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }

    // the rest of class definition
}

To initialize a new instance of the class with an initializer:

Book theBook = new Book { Title = "Don Quixote", Author = "Miguel de Cervantes" };

This is equivalent to

Book theBook = new Book();
theBook.Title = "Don Quixote";
theBook.Author = "Miguel de Cervantes";

Usage with anonymous types

Object initializers are the only way to initialize anonymous types, which are types generated by the compiler.

var album = new { Band = "Beatles", Title = "Abbey Road" };

For that reason object initializers are widely used in LINQ select queries, since they provide a convenient way to specify which parts of a queried object you are interested in.

var albumTitles = from a in albums 
                  select new 
                  { 
                     Title = a.Title, 
                     Artist = a.Band 
                  };

Usage with non-default constructors

You can combine object initializers with constructors to initialize types if necessary. Take for example a class defined as such:

public class Book {
    public string Title { get; set; }
    public string Author { get; set; }

    public Book(int id) {
        //do things
    }

    // the rest of class definition
}

var someBook = new Book(16) { Title = "Don Quixote", Author = "Miguel de Cervantes" }

This will first instantiate a Book with the Book(int) constructor, then set each property in the initializer. It is equivalent to:

var someBook = new Book(16);
someBook.Title = "Don Quixote";
someBook.Author = "Miguel de Cervantes";