In .NET < 3.5 the only collections you could initialize inline were arrays. So this was legal:
public class CollectionTest
{
public static readonly ICollection<string> _list =
new string[]{"one","two","three"};
}
However if you wanted to have List instead of array, you had to use a trick and pass array as constructor parameter:
public static readonly ICollection<string> _list =
new List<string>(new string[]{"one","two","three"});
Not the most elegant piece of code, but at least it works. So far so good. What if you wanted to have a IDictionary instead of ICollection? Well… in this case you’re out of luck, at least partially. To have a dictionary initialized, you’d have to use explicit static constructor, and it means – performance hit. Still, it’s better than nothing.
public class CollectionTest
{
public static readonly IDictionary<string,int> _dictionary =
new Dictionary<string,int>();
static CollectionTest()
{
_dictionary.Add("one",1);
_dictionary.Add("two",2);
_dictionary.Add("three",3);
}
}
But this all was in medieval times. Now, with object and collection initializers you can initialize any ICollection, the way you could with Arrays.
private static readonly ICollection<string> _list =
new List<string> {"one", "two", "three"};
This is neat, but even better stuff, is that you can do similar thing with Dictionaries, which means, no explicit static constructor required anymore.
private static readonly IDictionary<string, int>
_data = new Dictionary<string, int>
{
{"one", 1},
{"two", 2},
{"three", 3}
}:
Comments
anyway to make this work for .net 3.5 and VS 2005?
Bingo – right question… the described behavior is independent of .Net 3.5 as mentioned in this article, u need VS 2008. The "collection initializers" also work for project u develope for .Net 2.0 (i used it) and probably for .Net 1.1 (? but who would use .Net 1 at all ;))
Any way to make such dictionary case insensitive? So that _data["ONE"] also give 1 value.
Prakash – you can make it such by using appropriate constructor