![]() |
VOOZH | about |
In C#, object initializers and collection initializers are syntactic shortcuts that let you create objects and collections more concisely without explicitly calling multiple property setters or Add() methods.
An object initializer allows you to create an object and set its properties in a single statement, without needing a constructor that takes parameters for every property.
Syntax:
ClassName obj = new ClassName
{
Property1 = value1,
Property2 = value2,
Property3 = value3};
Example: In the below example, Geeks class doesn't contain any constructor, we simply created the object and initialized 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;
A collection initializer allows you to create a collection and populate it in a single statement, without calling Add() multiple times manually.
Syntax:
var collection = new CollectionType
{
item1,
item2,
item3};
Example :
b.01 and 405 b.09 and 234 b.11 and 395 b.55 and 500 b.67 and 100
1. You are allowed to initialize collection and the object at the same time.
Example:
2. You can also use null as an element in collection initializer.
Example: