locked
What are Object Initializers and Collection Initializers? RRS feed

  • Question

  • What are Object Initializers and Collection Initializers?


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.

    Tuesday, April 7, 2009 8:47 AM

Answers

  • Object Initializers

    Object initializers provide a way to assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

    Object initializers with named types

    Here we use auto-implemented properties featured in Visual C# 3.0 to define a class.  For details on auto-implemented properties, please check Auto-Implemented Properties (C# Programming Guide).

    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
    

     

    When we instantiate the objects of a Point class, we can use:

    Point p = new Point();
    p.X = 0;
    p.Y = 1;
    

     

    In Visual C# 3.0, there is a short way to achieve the same results:

    // {X = 0, Y = 1} is field or property assignments
    Point p = new Point { X = 0, Y = 1 }; 
    

     

    In LINQ, we can use named object initializer like this:

    The following example shows how we can use named object initializer with LINQ.  The example assumes that an object contains many fields and methods related to a product, but we are only interested in creating a sequence of objects that contain the product name and the unit price.

     var productInfos =
          from p in products
          select new { ProductName = p.ProductName, UnitPrice = p.UnitPrice };
    

     

    Collection Initializers

    Collection Initializers are similar in concept to Object Initializers.  They allow you to create and initialize a collection in one step.  By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

    List<int> numbers = new List<int> { 1, 100, 100 };

    In fact, it is the short form of the following:

    List<int> numbers = new List<int>();
    numbers.Add(1);
    numbers.Add(10);
    numbers.Add(100);
    

     

    Note:
    To be able to use a Collection Initializer on an object, the object must satisfy these two requirements:

    ·         It must implement the IEnumerable interface.

    ·         It must have a public Add() method.

    For additional information, please see Object and Collection Initializers (C# Programming Guide).

     

    For more FAQ about Visual C# General, please see Visual C# General FAQ

     


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.


    Tuesday, April 7, 2009 8:49 AM