How to: Initialize Objects by Using an Object Initializer (C# Programming Guide)

Switch View :
ScriptFree
Visual Studio 2010 - Visual C#
How to: Initialize Objects by Using an Object Initializer (C# Programming Guide)

Updated: July 2010

You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.

The following examples show how to use object initializers with named objects. The compiler processes object initializers by first accessing the default instance constructor, and then by processing the member initializations. Therefore, if the default constructor is declared as private in the class, object initializers that require public access will fail.

Anonymous types must be declared with an object initializer. For more information, see How to: Return Subsets of Element Properties in a Query (C# Programming Guide).

Example

The following example shows how to initialize a new StudentName type by using object initializers.

C#

public class Program
{
    public static void Main()
    {

        // Declare a StudentName by using the constructor that has two parameters.
        StudentName student1 = new StudentName("Craig", "Playstead");

        // Make the same declaration by using a collection initializer and sending 
        // arguments for the first and last names. The default constructor is 
        // invoked in processing this declaration, not the constructor that has
        // two parameters.
        StudentName student2 = new StudentName
        {
            FirstName = "Craig",
            LastName = "Playstead",
        };

        // Declare a StudentName by using a collection initializer and sending 
        // an argument for only the ID property. No corresponding constructor is
        // necessary. Only the default constructor is used to process object 
        // initializers.
        StudentName student3 = new StudentName
        {
            ID = 183
        };

        // Declare a StudentName by using a collection initializer and sending
        // arguments for all three properties. No corresponding constructor is 
        // defined in the class.
        StudentName student4 = new StudentName
        {
            FirstName = "Craig",
            LastName = "Playstead",
            ID = 116
        };

        System.Console.WriteLine(student1.ToString());
        System.Console.WriteLine(student2.ToString());
        System.Console.WriteLine(student3.ToString());
        System.Console.WriteLine(student4.ToString());
    }

    // Output:
    // Craig  0
    // Craig  0
    //   183
    // Craig  116
}

public class StudentName
{
    // The default constructor has no parameters. The default constructor 
    // is invoked in the processing of object initializers. 
    // You can test this by changing the access modifier from public to 
    // private. The declarations in Main that use object initializers will 
    // fail.
    public StudentName() { }

    // The following constructor has parameters for two of the three 
    // properties. 
    public StudentName(string first, string last)
    {
        FirstName = first;
        LastName = last;
    }

    // Properties.
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }

    public override string ToString()
    {
        return FirstName + "  " + ID;
    }
}


The following example shows how to initialize a collection of StudentName types by using a collection initializer. Note that a collection initializer is a series of comma-separated object initializers.

C#

List<StudentName> students = new List<StudentName>()
{
  new StudentName {FirstName="Craig", LastName="Playstead", ID=116},
  new StudentName {FirstName="Shu", LastName="Ito", ID=112},
  new StudentName {FirstName="Gretchen", LastName="Rivas", ID=113},
  new StudentName {FirstName="Rajesh", LastName="Rotti", ID=114}
};


Compiling the Code

To run this code, copy and paste the class into a Visual C# console application project that has been created in Visual Studio. By default, this project targets version 3.5 or a later version of the .NET Framework, and it has a reference to System.Core.dll and a using directive for System.Linq. If one or more of these requirements are missing from the project, you can add them manually. For more information, see How to: Create a LINQ Project.

See Also

Reference

Concepts

Change History

Date

History

Reason

July 2010

Added information about the role of the default constructor.

Customer feedback.

Community Content

SJ at MSFT
Misleading title
The title of this topic is misleading. In all cases, a constructor is being called - but it's the default constructor with no arguments.


SJ at MSFT: I recently updated this topic (and changed the name) to clarify the role of the default constructor. The changes will appear at the next refresh of the documentation. Thanks.