How to Initialize a Dictionary with a Collection Initializer
By Anuraj P on January 19th, 2011 . No Comments .
You can initialize any list and add items to inline using like the following.
List<Person> Persons = new List<Person>
{
new Person { Age = 20, Name = "Name" }
};
But this will not work Dictionary, if you try; you will get a compile time error like “No overload for method ‘Add’ takes 1 arguments”
You can fix this issue by putting a pair of curly braces.
Dictionary<int, Person> PersonsWithId = new Dictionary<int, Person>
{
{ 10, new Person { Age = 20, Name = "Name" } }
};
You can get more info about this MSDN
No Responses to “How to Initialize a Dictionary with a Collection Initializer”
RSS feed for comments on this post. TrackBack URL