Table of contents
1.
Introduction
2.
C# Object Initializer
2.1.
Example Code: 
2.1.1.
Output
2.2.
Explanation:
3.
C# Collection Initializer
3.1.
Example Code:
3.1.1.
Output
4.
Note:
5.
Frequently Asked Questions
5.1.
What is a class in C#?
5.2.
What is meant by structure in C#?
6.
Conclusion
Last Updated: Mar 27, 2024

Object and Collection Initializer in C#

Author Akash Nagpal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article we will be learning about Object Initializer and Collection Initializer with the help of suitable examples in C#. An object and collection initializer is a fascinating and beneficial feature of the C# programming language. This feature provides an alternative method for initializing a class or collection object. This functionality is available in C# 3.0 and later. The significant benefits of utilizing them are that they make your code more understandable, give a quick way to add components to collections, and are commonly used in multi-threading.

Recommended topics, Palindrome in C# and  Ienumerable vs Iqueryable

C# Object Initializer

An object initializer is used to set the value of a class's fields or properties when constructing an object without invoking a function Object() { [native code] }. This syntax allows you to construct an object, and then it assigns the newly generated object's properties to the variable in the assignment. This functionality was introduced in C# 6.0 and allowed it to put indexers for initializing fields and properties.

Example Code: 

 

// C# object initializer
using System;
 
class Coding Ninjas Studio {
 
    public string author_name
    {
        get;
        set;
    }
    public int author_id
    {
        get;
        set;
    }
    public int total_article
    {
        get;
        set;
    }
}
 
class Ninjas {
 
    // Main method
    static public void Main()
    {
 
        // Initialize fields using
        // an object initializer
        Coding Ninjas Studio obj = new Coding Ninjas Studio() {
            author_name = "Akash Nagpal",
            author_id = 123,
            total_article = 659};
         
        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: Akash Nagpal
Author Id: 123
Total no of articles: 659

Explanation:

Because the Coding Ninjas Studio class does not have a function Object(), we create the object and initialize the value using curly brackets in the main function. This process of initializing values is known as object initializer.

C# Collection Initializer

Collection initializers are comparable to object initializers. Collections are initialized in the same way as objects are by using an object initializer. In other words, whereas we often utilize the Add() function to add elements to collections, you may add elements without using the Add() method when using a collection initializer.

Example Code:

// C# collection Initializer
using System;
using System.Collections;
 
class Coding Ninjas Studio {
 
    // Main Method
    static public void Main()
    {
 
        // Creating another SortedList
        // using collection Initializer to
        // initialize sortedlist
        SortedList my_slist = new SortedList() {
                             { "b.09", 789 },
                             { "b.11", 807 },
                             { "b.01", 211 },
                             { "b.67", 157 },
                             { "b.55", 578 }};
        
        foreach(DictionaryEntry pair in my_slist)
        {
            Console.WriteLine("{0} and {1}", pair.Key, pair.Value);
        }
    }
}

Output

b.01 and 211
b.09 and 789
b.11 and 807
b.55 and 578
b.67 and 157

Note:

We can use initialize collection with the object at the same time, 

For Example: 

var author1 = new Coding Ninjas Studio() { author_name = "Akash",
                            author_id = 123,
                            total_article = 45 };
 
var author2 = new Coding Ninjas Studio() { author_name = "Pranchal",
                            author_id = 326,
                            total_article = 370 };
 
var author3 = new Coding Ninjas Studio() { author_name = "Apurv",
                            author_id = 911,
                            total_article = 200 };
 
List<Coding Ninjas Studio> author = new List<Coding Ninjas Studio>() {
                                author1,
                                author2,
                                author3
};

Recommended Topic: Multithreading in C#, singleton design pattern in c#, Multithreading in Python

Frequently Asked Questions

What is a class in C#?

A class in C# is a user-defined blueprint for creating objects. It combines many forms of data into a single unit.

What is meant by structure in C#?

A structure in C# is a composite data type made up of numerous data types such as methods, fields, constructors, constants, properties, indexers, operators, and even other structures.

A structure helps in merging different data kinds into a single entity. They are comparable to courses in this regard. On the other hand, structures are value types, whereas classes are reference types.

Conclusion

In this article, we have extensively discussed Object and Collection Initializer in C#. We have also discussed different the above-mentioned topics with the help of suitable examples.

We hope this blog has helped you enhance your knowledge regarding the C# language. Some official documentation on big data that can help you improve your understanding is C# Generics and C# Inheritance.

If you would like to learn more, check out our articles on Operator Keyword in C#cloud platform comparison, and 10 AWS best books

Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass