Dictionary Initializer - C# 6 Language New features

Dictionary Initializer has existed feature since C# 3. Microsoft enhanced this feature in C# 6 by adding ability to directly initialize a value of a key. Today, I am going to share one of the new feature of C# 6 "Dictionary Initializer". We will discuss How Microsoft change from existing Dictionary Initializer syntax to new Index initializer feature while you are initializing dictionary.

Dictionary is used to represent a collection of Key and value pairs. Most developers use a Dictionary for keeping a generic collection of data. You can use a HashTable for same, but Dictionary has more powerful features than the HashTable.
In previous C# versions, we have to use curly braces for initialize value.
Dictionary<int, string> dic = new Dictionary<int, string>()
{
     {1, "USA"},
     {2, "INDIA"},
     {3, "UK"},
     {4, "AUS"}
};
In C# 6, you get simpler and cleaner approach to initialize your dictionary.The new syntax is significant clear and save your few key strokes. C# 6.0 makes this possible through the C# object initializers and a new index member syntax.
<index> = <value>
How to use
Dictionary <int, string> dic = new Dictionary<int, string>()
{
    [1] = "USA",
    [2] = "INDIA",
    [3] = "UK",
    [4] = "AUS"
};
If you want to add new elements in the collection, it's so easy now.
dic[5] = "CHINA";
dic[6] = "JAPAN";
Conclusion : Index initializer is already exists in array and other, Microsoft just uses the same concept for the Dictionary. That's make Dictionary Initiazlier more clean and simple.

Comments

Popular posts from this blog

12 opensource and free asp.net MVC gridview contols

Scheduling background jobs using Hangfire in ASP.NET Core

Difference ExecuteNonQuery vs ExecuteScalar vs ExecuteReader in asp.net