Converting Dynamic Types to Generic Parameters
There is a problem when an API uses a Generic Parameter as a Type reference.
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);
Recent Posts
- Top 5 questions to ask when checking references
- Unacceptable: Unit testing will take 20 years to catch on
- The 4 reasons why we DIDN’T choose Oslo
- Typemock Academy Launch
- The First Rule to Software Craftsmanship
Categories
- .NET Tests
- Agile
- Code Integrity
- Community
- Debugging
- Fun
- Management for Geeks
- Marketing
- Product
- Release
- Reviews
- SharePoint
- TDD
- Time Management
- Uncategorized
- Unit Tests
Archives
- August 2010
- May 2010
- April 2010
- March 2010
- February 2010
- December 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- December 2008
- November 2008
- August 2008
- July 2008
- May 2008
- April 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
- April 2007
- March 2007
- February 2007
- January 2007
- December 2006
- November 2006
- October 2006
- September 2006
