C# Language Reference
How to: Initialize Objects without Calling a Constructor (C# Programming Guide)

Updated: July 2009

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

The following examples show how to use object initializers with named objects. 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.
        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
        // defined in the class.
        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
{
    // Default constructor has no parameters.
    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 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

Concepts

Reference

Change History

Date

History

Reason

July 2009

Expanded the examples.

Customer feedback.

Tags : przeczytane


Community Content

MEta_COg
Misleading information...
This does not prevent the need to call a constructor. The default constructor of the type will still be called. That means this will not work if the type has a private parameterless constructor, as the default constructor will not be accessible. This will also not help avoid situations in which a new instance is needed of a type that is unknown until runtime. There is a need for a way to create a new instance of a type, without calling any constructor, as the types default constructor may not be accessible, or it may perform actions that are undesired.

public class TestClass1 {
public TestClass1() {
Console.WriteLine("TestClass1 constructor called.");
}}

public class TestClass2 {
private TestClass2() {
Console.WriteLine("TestClass2 constructor called.");
}}

//////////////////

static void Main() {
TestClass1 test1 = new TestClass1 { }; // Output: TestClass1 constructor called.
TestClass2 test2 = new TestClass2 { }; // Compile error, TestClass2.TestClass2()' is inaccessible due to its protection level
}




Tags :

Page view tracker