C# Language 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";