Reflection cheat

Today I needed to retrieve a Type by name, but from a foreign assembly.  Without going into the gory details, it’s related to instantiating Windows Workflow Foundation’s RuleSetDialog after a rule has been loaded in from a database.

I could have made a call to Assembly.GetExecutingAssembly().GetReferencedAssemblies(), and iterated over the results looking for the one I wanted, but I’d still have to end up looking for it by name, and anyone who knows me knows that I hate string comparisons.  Since I already knew what assembly the thing I’m looking for is in, that also seems like a waste of time.  So I found a bit of a cheat.  I’m happy enough with it to put it here in the hopes that it will be useful to someone else someday.

Since I already know what assembly my business entities are in, I should be able to get a reference to the assembly by starting with one of the types from there.  In this case I chose the BusinessEntityBase class because it’s nicely meaningless on its own, and because the whole world would collapse anyway if this class were to be moved or renamed, so it seems like a stable thing to anchor myself to.  From there, I can easily get to that type’s Assembly property, and call GetType() on it, passing the name of the actual business entity I really want.  Here it is in its full two lines of glory.

Type businessEntityBaseType = typeof(BusinessEntityBase);
Type entityType = businessEntityBaseType.Assembly.GetType(typeName);

Here, typeName is a string containing the fully qualified name of the business entity I want to edit a rule for.

This entry was posted in Computers and Internet. Bookmark the permalink.

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