0

The requirement is like this. Now I have a Dictionary.

Dictionary<int,string> dic = new Dictionary<int,string>();
//... some other operations
Type t = typeof(Dictionary<int,string>);

Now I want to get the type int and string. How can I get the two? Thank you very much.

Update:

Thank you for the response. Actually my requirement is to create another generic class based on the two types, which were got from the dictionary type. Just like this.

PropertyType propertyType = typeof(Dictionary<int,string>);
if (propertyType.Name.Contains("Dictionary"))
{
    Type keyType = propertyType.GetGenericArguments()[0];
    Type valueType = propertyType.GetGenericArguments()[1];
    propertyType = typeof(SerializableDictionary<keyType, valueType>);
}
//And after this, it will dynamically create a class and add the propery as one
//of its properties

Now I cannot use propertyType = typeof(SerializableDictionary<keyType, valueType>). How should I update this statement? Thank you.

Sun Robin
  • 583
  • 4
  • 13

1 Answers1

5

Here is a snippet:

Type keyType = t.GetGenericArguments()[0];
Type valueType = t.GetGenericArguments()[1];

Update:

var typeOfNewDictonary = typeof(SerializableDictionary<,>)
                               .MakeGenericType(new[] 
                                           { 
                                               keyType, 
                                               valueType 
                                           });

BTW: The following line is wrong:

PropertyType propertyType = typeof(Dictionary<int,string>);

It should be rather:

Type propertyType = typeof(Dictionary<int,string>);

What's more, condition in if (propertyType.Name.Contains("Dictionary")) has no sense. It always be evaluated as true.