Converting Dynamic Types to Generic Parameters

There is a problem when an API uses a Generic Parameter as a Type reference.image Although having a generic parameter makes the code Type Safe

SafeType MyApi<SafeType>();

It is really hard to use the API in dynamic way. So if we receive a Type in a variable there is no easy way to call the generic method.

Type myType = GetTypeToUse();
var ret = MyApi<myType>();
//              ^^^^^^ Error

One way to do this (convert a dynamic type to a generic type) is via reflection (See example on the Typemock Blog)

private static object MyApi(Type ofType)
{
 MethodInfo myApiMethod = typeof(MyAssembly)
     .GetMethod("MyApi").MakeGenericMethod(ofType);
 return myApiMethod.Invoke(null, null);
}

or we can cache the MethodInfo

private static MethodInfo myApi = typeof(MyAssembly).GetMethod("MyApi");
private static object MyApi(Type ofType)
{
 MethodInfo myApiMethod = myApi.MakeGenericMethod(ofType);
 return myApiMethod.Invoke(null, null);
}

When designing an API we should think of developers who receive the Type in a dynamic way, and have an embedded API to handle this from the start.

// Type Safe API
SafeType MyApi<SafeType>();
// Dynamic Type API object MyApi(Type ofType);

10 May 2009 | .NET Tests | Comments | Print This Post

Leave a Reply

  1.  
  2.  
  3.  
Search Development and Integrity Management by Eli Lopian

Navigation

Recent Posts

Categories

Archives

Managment