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.