What happens when you need to pass a type as a string? Well, if the string is an assembly qualified type name, and if the assembly is either in Global Assembly Cache or in a known location – such as the Bin folder or a probed path – you’re likely to succeed. But, what if that isn’t the case? Well, we can follow these steps:
- Try to locate the type the usual way, by calling Type.GetType;
- Look the type in the current executing, entry and calling assemblies;
- Look it up in all of the loaded assemblies for the current domain (could be a lot);
- Hook up the TypeResolve event of the current app domain (I am not going to show that).
Normally, in .NET we use type converters for doing this kind of stuff in configuration files or ASP.NET markup. Following that, a type converter for turning a string into a type might look like this:
We just need to apply a TypeConverterAttribute attribute to a property and the magic occurs naturally:
Or if we need to invoke it explicitly:
And that’s it. Keep in mind that it is always preferable that you specify an assembly qualified type name, but if that can’t be done, this might come in handy.