GetType From All The Things


Lets say you have a Model.  The name of the model is stored in a string somewhere, and you want to get a reference to do something with that model.  How do you do it?

Type.GetType(<string>) is the advertised way, but there are a lot of limitations on that.  Primarily assembly location, and FullName versus Name.  I ran into this conundrum in a small C# application, and wound up with this solution:

 public static Type GetType(string name)
 {
    var type = Type.GetType(name);
    if (type != null) return type;

    foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
    {
       type = a.GetTypes().FirstOrDefault(x => x.Name == name);
       if (type != null) return type;
    }

    return null;
 }

Fundamentally this runs a normal Type.GetType, but then looks in all loaded assemblies to try to find anything that matches by Name.  This could be extended to do fuzzy matching by Name, match by Name or FullName, or a combination of things, but this worked for my use case.  It’s not pretty, and for a large application may not be very efficient, but it gets the job done.  Maybe it’ll get a job done for you too?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s