Object and Collection Initializer in C#

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

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

Note: When the compiler compiles the above program it assigne 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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
        }
    }
}

chevron_right


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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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
    };

    chevron_right

    
    

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

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.