Reputation: 837
I am trying to dynamically create a generic Dictionary based on the type of a property in the following class:
public class StatsModel
{
public Dictionary<string, int> Stats { get; set; }
}
Let's assume the System.Type of the Stats property is assigned to a variable 'propertyType' and that the IsGenericDictionary method returns true if the type is a generic dictionary. I then use Activator.CreateInstance to dynamically create a generic Dictionary instance of the same type:
// Note: property is a System.Reflection.PropertyInfo
Type propertyType = property.PropertyType;
if (IsGenericDictionary(propertyType))
{
object dictionary = Activator.CreateInstance(propertyType);
}
Since I already know that the object that is created is a generic dictionary I would like to cast to a generic dictionary whose type arguments equal the generic arguments of the property type:
Type[] genericArguments = propertyType.GetGenericArguments();
// genericArguments contains two Types: System.String and System.Int32
Dictionary<?, ?> = (Dictionary<?, ?>)Activator.CreateInstance(propertyType);
Is this possible?
Upvotes: 4
Views: 7955
Reputation: 1064204
If you want to do that, you'll have to use reflection or dynamic
to flip over into a generic method, and use the generic type arguments. Without that, you have to use object
. Personally, I'd just use the non-generic IDictionary
API here:
// we know it is a dictionary of some kind
var data = (IDictionary)Activator.CreateInstance(propertyType);
which gives you access to the data, and all the usual methods you expect on a dictionary (but: using object
). Flipping into a generic method is a pain; to do it pre-4.0 requires reflection - specifically MakeGenericMethod
and Invoke
. You can, however, cheat in 4.0 using dynamic
:
dynamic dictionary = Activator.CreateInstance(propertyType);
HackyHacky(dictionary);
with:
void HackyHacky<TKey,TValue>(Dictionary<TKey, TValue> data) {
TKey ...
TValue ...
}
Upvotes: 7