Hi there,
I was wondering what is the best way for getting the generic arguments that definine a dictionary at run time is.
Take for example:
Dictionary<string, object> dict;
How at runtime can I find out that the keys are strings?
Thanks
Hi there,
I was wondering what is the best way for getting the generic arguments that definine a dictionary at run time is.
Take for example:
Dictionary<string, object> dict;
How at runtime can I find out that the keys are strings?
Thanks
I'm not sure if I understand your question correctly but I think you mean something like this:
Dictionary<string, object> dict = new Dictionary<string, object>();
// ...
var args = dict.GetType().GetGenericArguments();
// args[0] will be typeof(string)
Here's an NUnit test to demonstrate Mehrdad's answer, and with a dictionary containing integers as keys, and strings as values:
[Test]
public void testGetPhysicalTypeForGenericDictionary()
{
IDictionary<int, string> myDictionary = new Dictionary<int, string>();
Type [] myTypes = myDictionary.GetType().GetGenericArguments();
Assert.AreEqual(2, myTypes.Length);
var varTypes = myDictionary.GetType().GetGenericArguments();
Assert.AreEqual("Int32", varTypes[0].Name);
Assert.AreEqual("System.Int32", varTypes[0].FullName);
Assert.AreEqual("String", varTypes[1].Name);
Assert.AreEqual("System.String", varTypes[1].FullName);
}