What are Object Initializers and Collection Initializers in C#?

Object Initializers

Object initializers facilitates assignment of 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
In this example, we use auto-implemented properties to define a class.
public class Point
    public int iXPoint { get; set; }
    public int iYPoint { get; set; }
During instantiation of the objects of the Point class, we can use:
Point oPoint = new Point();
oPoint.iXPoint = 0;
oPoint.iYPoint = 1;
Given below is a shorter technique to implement the above declaration and assignments:
// {iXPoint = 0, iYPoint = 1} is field or property assignments
Point oPoint = new Point { iXPoint = 0, iYPoint = 1 };  
In LINQ, we can use named object initializer as given below:
The following example shows the technique to use named object initializer with LINQ. The example below 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 and allows you to create and initialize a collection in a single step. During implementation of 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 by itself.
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>();
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.

No comments:

Post a Comment