Wednesday, 29 May 2013

Why does System.GetType return null–Why doesn’t my app work on WP8 (part 3 of N)

While porting our Skied Demon Ski logger app to Windows Phone 8 to support background location services and new wide tiles, we stumbled across a problem calling

System.GetType(“typename, assemblyname”) where it would always return null.

While GetType worked with a fully qualified assembly name, that struck me as bad for maintainability as I’d have to remember to change it whenever something changed, and because it was loaded by reflection, it wasn’t likely to go away completely.

After some investigation, I finally came up with this helper method:

static Type GetTypeEx(string typename, string assemblyname)
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
if (a.GetName().Name == assemblyname) return a.GetType(typename);
return null;

So I now call it like this:

GetTypeEx(“typename”, “assemblyname”);

I only do this a couple of places in the software, but if I were to make heavy use of reflection, I’d probably cache the assembly references into a dictionary to save the iteration.

No comments:

Post a Comment