This is what I need to do:
object foo = GetFoo();
Type t = typeof(BarType);
(foo as t).FunctionThatExistsInBarType();
Can something like th
Since dynamics were added to c#, I think we can do it in this way:
class Program {
static void Main(string[] args) {
List c = new List();
double i = 10.0;
Type intType = typeof(int);
c.Add(CastHelper.Cast(i, intType)); // works, no exception!
}
}
class CastHelper {
public static dynamic Cast(object src, Type t) {
var castMethod = typeof(CastHelper).GetMethod("CastGeneric").MakeGenericMethod(t);
return castMethod.Invoke(null, new[] { src });
}
public static T CastGeneric(object src) {
return (T)Convert.ChangeType(src, typeof(T));
}
}