No doubt elements of this question have been asked before, but I’m having trouble finding an answer. (Disclaimer: this is related, but separate from a recent question I asked).
I have a method like this:
public static void Method<T>(MethodInfo m, T value)
{
Type memberType = m.GetValueType();
if (memberType.IsAssignableFrom(typeof(List<T>))
{
object memberValue = Activator.CreateInstance(memberType);
((List<T>)memberValue).Add(value);
}
}
This works fine when I call it like this:
string s = "blah";
Method(memberInfo, s);
However, I need to call this method using a generic type, so I’m calling it like this:
Type valueType = someType;
object passValue = someMethod.MakeGenericMethod(new Type[] { valueType }).Invoke(this, new object[] { });
/* Call my original method */
Method(memberInfo, passValue );
Now, intellisense knows that ‘value’ in Method<T> is whatever type valueType is (say ‘FooObject’). But ‘T’ is object, which means that a List<FooObject> is not assignable from a List<T> (i.e. a List<object>).
I’ve tried using Convert.ChangeType on the variable (‘passValue’) beforehand but that wasn’t any more useful.
As there is no way to cast a variable to the Type of a type variable, how do I get around this?
Is the best solution to somehow not rely on IsAssignableFrom and do a looser type check of whether this will work? The problem with this is that I’m not sure I’ll be able to cast the memberValue properly unless ‘T’ is truly the element type of memberValue.
You’re in luck. I actually had to do something very similar a few weeks ago.
For a detailed explanation see the above blog post, but basically the general idea is to reflect the type and manually invoke the method with an explicit set of parameters.
It’s not
verytype safe, but it does exactly what you’re looking for.Output