How to initialize IDictionary in constructor?
asp.net-mvc, c#
Solution
The following blog post has a helper method that can create Dictionary objects from anonymous types.
http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx
void CreateADictionaryFromAnonymousType()
{
var dictionary = MakeDictionary(new {Name="Roy",Country="Israel"});
Console.WriteLine(dictionary["Name"]);
}
private IDictionary MakeDictionary(object withProperties)
{
IDictionary dic = new Dictionary<string, object>();
var properties =
System.ComponentModel.TypeDescriptor.GetProperties(withProperties);
foreach (PropertyDescriptor property in properties)
{
dic.Add(property.Name,property.GetValue(withProperties));
}
return dic;
}
Problem
In TagBuilder and other classes I can write something like: ``` var tr = new TagBuilder("HeaderStyle"){InnerHtml = html, [IDictionary Attributes]} ``` but I don't know how to pass the IDictionary parameter. How can I do that on the fly? Without creating a Dictionary variable. TagBuilder is an example, there are other classes that accept a parameter `IDictionary`as well. The question is about the generic case.