The Dictionary Initializer was introduce in C#6.0, Visual Studio 2015 and .NET 4.6. By using this, we can map the indexer at the time of dictionary object initialization. In this article, we will look into how to use the same with an example.
Introduction
The Dictionary Initializer was introduce in C#6.0, Visual Studio 2015 and .NET 4.6. By using this, we can map the indexer at the time of dictionary object initialization. In this article, we will look into how to use the same with an example.
Straight to experiment
Object creation
Let us first create two classes say Class1 and Class2 as under
internal class Class1
{
public string ClassMethod()
{
return "From Class 1";
}
}
internal class Class2
{
public string ClassMethod()
{
return "From Class 2";
}
}
Add the objects to the Dictionary by using the new C# 6.0 Dictionary Initializer way
Then create a Dictionary Initializer as under
private static Dictionary<string, Type> ObjectTypes()
{
return new Dictionary<string, Type>
{
["Class1"] = typeof(Class1),
["Class2"] = typeof(Class2)
};
}
Prior to C#6.0, we used to use the dictionary initializer to initialize dictionary objects with key and values
as shown below
private static Dictionary<string, Type> ObjectTypes()
{
return new Dictionary<string, Type>
{
{"Class1", typeof(Class1)},
{"Class2", typeof(Class2)}
};
}
But C# 6.0, has enhanced this feature by making the keys as indexers that brings more readability in the code.
Read the values from the Dictionary
Now we can read the values from the Dictionary in the same way as we are used to
private static dynamic GetObject(string key)
{
return Activator.CreateInstance(ObjectTypes()[key]) as dynamic;
}
We are passing the "key" and getting the value from the Dictionary object and then creating the object instance at run time. Since we want to use the object methods/properties at run time, we are casting it into dynamic.
Client Invocation
Now let's invoke the dictionary as under
GetObject("Class1").ClassMethod();
The method "ClassMethod()" is invoked at run time.
A complete implementation is as under
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetObject("Class1").ClassMethod());
Console.ReadKey();
}
private static dynamic GetObject(string key)
{
return Activator.CreateInstance(ObjectTypes()[key]) as dynamic;
}
private static Dictionary<string, Type> ObjectTypes()
{
return new Dictionary<string, Type>
{
["Class1"] = typeof(Class1),
["Class2"] = typeof(Class2)
};
}
}
internal class Class1
{
public string ClassMethod()
{
return "From Class 1";
}
}
internal class Class2
{
public string ClassMethod()
{
return "From Class 2";
}
}
}
The result is From Class 1
Conclusion
In this article we have learnt about the Dictionary Initializer of C# 6.0. Hope this will be helpful. Thanks for reading.