Can anyone explain how to get this to work? I am passing in the type name, and “t” is being correctly populated. I just cannot figure out how to cast objectToCast to type “t”. Any help is appreciated.
....
Type t = Type.GetType("castToTypeNameHere");
o = CastTo<t>(objectToCast);
....
private T CastTo<T>(Object obj)
{
return (T)obj;
}
FYI, here’s the answer I found:
Type t = Type.GetType(element.Attribute("castToType").Value);
MethodInfo castMethod = this.GetType().GetMethod("CastTo", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(t);
object castedObject = castMethod.Invoke(this, new object[] { objectToCast });
When you use generics (without reflection), the type parameters have to be the name of types, not instances of
System.Type. So you can’t saybecause
tis not the name of a type. It’s as if you had saidinstead of
The former is illegal, the latter is legal.
I don’t understand what you’re trying to achieve. If you don’t know the type at compile time, a cast like that is useless. The compiler won’t know the type of
o, and you won’t get any of the compile-time type safety nor IntelliSense features.