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.
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.
b.01 and 405 b.09 and 234 b.11 and 395 b.55 and 500 b.67 and 100
- You are allowed to initialize collection and the object at the same time.
- You can also use null as an element in collection initializer.