In this article, you will learn:
- How to initialize Dictionary before C# 6.0 ?
- How to initialize Dictionary in C# 6.0
How to initialize Dictionary before C# 6.0 ?
In C# 5, you would initialize the Dictionary with a {“Key”, “Value”} Pair. Let’s look at below example to understand it better.
Prior to C# 6.0:
using System.Collections.Generic;
namespace CsharpStar
{
class Program
{
static void Main(string[] args)
{
var Books = new Dictionary<int, string> ()
{
{ 1, "ASP.net" },
{ 2, "C#" },
{ 3, "ASP.net MVC5" }
};
foreach (KeyValuePair<int, string> keyValuePair in Books)
{
Console.WriteLine(keyValuePair.Key + ": " +
keyValuePair.Value + "\n");
}
Console.ReadLine();
}
}
}Example in C# 6.0:
In C# 6, you can place the key between two square brackets [“Key”] and then set the value of the key [“Key”] = “value”.
using System.Collections.Generic;
using static System.Console;
namespace Csharpstar
{
class Program
{
static void Main(string[] args)
{
var Books = new Dictionary<int, string> ()
{
[1] = "ASP.net",
[2] = "C#",
[3] = "ASP.net MVC5"
};
foreach (KeyValuePair<int, string> keyValuePair in Books)
{
WriteLine(keyValuePair.Key + ": " +
keyValuePair.Value + "\n");
}
ReadLine();
}
}
}Advantages:
– You can create and initialize objects with indexes at the same time.
– Initializing Dictionary is very easy with this new feature
– Any object that has an indexed getter or setter can be used with this syntax
Thanks for visiting !!
© 2016, Csharp Star. All rights reserved.
