Dictionary Initializers
For Dictionary, In C#6 you can Initializes in much easier way.
In earlier version, if you have to initilize the Dictionary, you have to write
{"Key", "Value"}.
Now you can initilize like this ["Key"] = value.
See below example:
Before C#6
using System;
using System.Collections.Generic;
namespace NewInCSharp6
{
class Program
{
private static void Main(string[] args)
{
Dictionary<string, string> FullName = new Dictionary<string, string>()
{
{ "FirstName", "Peter" },
{ "LastName","Hansen" }
};
foreach (KeyValuePair<string, string> keyValuePair in FullName)
{
Console.WriteLine(keyValuePair.Key + ": " + keyValuePair.Value + "\n");
}
Console.ReadLine();
}
}
}
After C#6
using System;
using System.Collections.Generic;
using static System.Console;
namespace NewInCSharp6
{
class Program
{
private static void Main(string[] args)
{
Dictionary<string, string> FullName = new Dictionary<string, string>()
{
// see the new syntax. Easy to use.
["FirstName"]= "Peter" ,
["LastName"]= "Hansen"
};
foreach (KeyValuePair<string, string> keyValuePair in FullName)
{
WriteLine(keyValuePair.Key + ": " + keyValuePair.Value + "\n");
}
ReadLine();
}
}
}
C# 6.0 Feature: Dictionary Initializers
Reviewed by kamal kumar das
on
November 25, 2016
Rating:

No comments: