Id like to be able to work with Dictionaries in generic methods. What Im looking for is a way to get the Type from Key and Value of the dictionary sent to the generic extension method LoadProperty.
This is what I’ve done so far.
I call the method as an extension
entityObject.LoadProperty<Dictionary<string, int>>("CartonThreshold")
//entityObject.LoadProperty<Dictionary<string, double>>("CartonThreshold")
// ...
public static T LoadProperty<T>(this EntityObject entity, string name) where T : new()
{
EntityObjectProperty prop = entity.Properties.Single(x => x.Name.Equals(name));
// If request dictionary
if (typeof(T).GetInterface(typeof(IDictionary<,>).Name) != null || typeof(T).Name.Contains("IDictionary"))
{
var dictionaryInstance = (IDictionary)new T();
// Just for testing
var a = dictionaryInstance.Keys.GetType().Name;
var b = dictionaryInstance.Values.GetType().Name;
var key = (T) Convert.ChangeType(prop.Name, typeof (T));
var value = (T) Convert.ChangeType(prop.Value, typeof (T));
dictionaryInstance.Add(key, value);
return (T) dictionaryInstance;
}
// default
return (T)Convert.ChangeType(prop.Value, typeof(T));
}
The goal is to return a correctly typed dictionary
What I was looking for was the GetGenericArguments() extension of GetType()
The method below will return what I need.
This way I can call the method like this