Open In App

Object and Collection Initializer in C#

Improve
Improve
Like Article
Like
Save
Share
Report

An object and collection initializer is an interesting and very useful feature of C# language. This feature provides a different way to initialize an object of a class or a collection. This feature is introduced in C# 3.0 or above. The main advantages of using these are to makes your code more readable, provide an easy way to add elements in collections, and mostly used in multi-threading.
 

Object Initializer in C#

In object initializer, you can initialize the value to the fields or properties of a class at the time of creating an object without calling a constructor. In this syntax, you can create an object and then this syntax initializes the freshly created object with its properties, to the variable in the assignment. It can also place indexers, to initializing fields and properties, this feature is introduced in C# 6.0.
Example: In the below example, Geeks class doesn’t contain any constructor, we simply create the object and initialize the value at the same time using curly braces in the main method. This initializing of values is known as object initializer.

CSharp




// C# program to illustrate
// object initializer syntax
using System;
 
class Geeks {
 
    public string author_name
    {
        get;
        set;
    }
    public int author_id
    {
        get;
        set;
    }
    public int total_article
    {
        get;
        set;
    }
}
 
class GFG {
 
    // Main method
    static public void Main()
    {
 
        // Initialize fields using
        // an object initializer
        Geeks obj = new Geeks() {
            author_name = "Ankita Saini",
            author_id = 102,
            total_article = 178};
         
        Console.WriteLine("Author Name: {0}", obj.author_name);
 
        Console.WriteLine("Author Id: {0}", obj.author_id);
 
        Console.WriteLine("Total no of articles: {0}",
                                   obj.total_article);
    }
}


Output: 

Author Name: Ankita Saini
Author Id: 102
Total no of articles: 178

 

Note: When the compiler compiles the above program it assign the values to the object as shown below:

Geeks __geeks = new Geeks();
__geeks.author_name = "Ankita Saini";
__geeks.author_id = 102;
__geeks. total_article = 178;

Geeks obj =  __geeks; 

Collection Initializer in C#

Collection initializer is also similar to object initializers. The collections are initialized similarly like objects are initialized using an object initializer. Or in other words, generally, we used the Add() method to add elements in collections, but using a collection initializer you can add elements without using Add() method.
Example :

CSharp




// C# program to illustrate how
// to create a SortedList using
// collection Initializer
using System;
using System.Collections;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Creating another SortedList
        // using  collection Initializer to
        // initialize sortedlist
        SortedList my_slist = new SortedList() {
                             { "b.09", 234 },
                             { "b.11", 395 },
                             { "b.01", 405 },
                             { "b.67", 100 },
                             { "b.55", 500 }};
        
        foreach(DictionaryEntry pair in my_slist)
        {
            Console.WriteLine("{0} and {1}", pair.Key, pair.Value);
        }
    }
}


Output: 

b.01 and 405
b.09 and 234
b.11 and 395
b.55 and 500
b.67 and 100

 

Important Points:

  • You are allowed to initialize collection and the object at the same time.
    Example:

CSharp




var author1 = new Geeks() { author_name = "Soniya",
                            author_id = 103,
                            total_article = 120 };
 
var author2 = new Geeks() { author_name = "Siya",
                            author_id = 106,
                            total_article = 90 };
 
var author3 = new Geeks() { author_name = "Arpita",
                            author_id = 111,
                            total_article = 130 };
 
List<Geeks> author = new List<Geeks>() {
                                author1,
                                author2,
                                author3
};


  • You can also use null as an element in collection initializer.
    Example:

CSharp




SortedList my_slist = new SortedList() {
                          { 1.2, "Cat" },
                          { 1.3, null },
                          { 1.5, 234 },};




Last Updated : 24 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads