In the example bellow, is it possible to set the Classname type parameter dynamically?
UpdateAndSave<Classname>>().Execute(sql)
In the example bellow, is it possible to set the Classname type parameter dynamically?
UpdateAndSave<Classname>>().Execute(sql)
If your type is coming from an object, then you can cheat using dynamic
- hijacking it to perform (and cache, via meta-programming etc) the type resolution for you. For example - if you currently have:
object obj = ...
Type type = obj.GetType();
// now want to call UpdateAndSave<type>(...)
then you can do:
public void Voodoo<T>(T obj, string sql) {
UpdateAndSave<T>().Execute(sql);
}
and just:
object obj = ...
Voodoo((dynamic)obj, sql);
The runtime will detect the type of obj
, determine the best overload to use (which will be Voodoo<TheActualType>(...)
), and call that. Plus it will cache the strategy for that type, so it is fast next time (it only does any significant work once per unique type).
Well you can call it by reflection, yes - using MethodInfo.MakeGenericMethod
to provide the type arguments:
var method = typeof(Whatever).GetMethod("UpdateAndSave");
var genericMethod = method.MakeGenericMethod(typeArgument);
genericMethod.Invoke(target, new object[] { sql });