I have a big dictionary of (string, object). The values in the dictionary are of different types. Only at run time I can find the exact type of the values in the dictionary of (string, int) or (string, string). At run time I have to assign the values in the dictionary to their corresponding strongly typed objects. This is the simplified problem.
I’m trying to use a typed class that does the cast.
I have this code that does not work:
static void Main(string[] args)
{
var values = new Dictionary<string, object>
{
{ "123", "test"},
{"12", 123}
};
var result = new Dictionary<string, object> ();
Type dict = values.GetType();
Type typedCast = typeof(TypedClass<>).MakeGenericType(new [] { dict });
MethodInfo method = typedCast.GetMethod("GetTypedValue",
BindingFlags.Static | BindingFlags.Public,
null,
new[]
{
typeof(object),
typeof(object).MakeByRefType()
},
null);
method.Invoke(null, new[]{values, result});
}
public class TypedClass<T>
{
public static void GetTypedValue(object value, out object obj)
{
obj = (T)Convert.ChangeType(value, typeof(T));
}
}
Inside the GetTypedValue method I see the obj value with the correct type, but outside this method the out variable has no values. Please let me know what am I doing wrong.
Try replacing:
with
In any case, I’m not sure why you would want to convert the type of a Dictionary to another Dictionary, because that’s what your code seems to do…