Type.GetType issues

J

Jamey McElveen

I have the typename of a form I wish to to load dynamically
(example:MyCompany.Client.Win.Security.Detail.SysUserDetailForm).
However, when I call Type.GetType(typeName) it return null I am assuming
since I did not use the full name which is not available. I wrote the below
method to return the Type but I have some concerns with it.

First is there an eaiser way to do this that I am missing. Second, I am
concerned about the Assembly.Load(assemblyName); call am I loading the
referenced assembly or another instance of the same assembly?

Thanks

/// <summary>
/// Searches all Types in this and referenced Assemblies for the
/// specified type. If the type is not found FindType returns null.
/// If the type is found in more thatn one Assmebly FindType raises
/// an exception.
/// </summary>
/// <param name="typeName">Name of the type.</param>
/// <returns>Returns the Type or null if it cannot be
found</returns>
public static Type FindType(string typeName)
{
Type result = null;
int findCount = 0;

// Iterrate through the local assembly first.
Assembly root = Assembly.GetExecutingAssembly();
foreach (Type type in root.GetTypes())
{
if (type.FullName.Equals(typeName))
{
if (result == null)
result = type;
findCount++;
}
}

// Iterrate through all referenced assemblies
foreach (AssemblyName assemblyName in
root.GetReferencedAssemblies())
{
Assembly referencedAssembly = Assembly.Load(assemblyName);
foreach (Type type in referencedAssembly.GetTypes())
{
if (type.FullName.Equals(typeName))
{
if (result == null)
result = type;
findCount++;
}
}
}

if (findCount > 0)
throw new Exception(string.Format("An ambiguous type error
has occurred in the method FindType. More that one Type exists with the
name {0}.", typeName));

return result;
}
 
M

Mattias Sjögren

Jamey,
First is there an eaiser way to do this that I am missing.

Where do you get the type name from? Can't you store the assembly name
with the type name?
Second, I am
concerned about the Assembly.Load(assemblyName); call am I loading the
referenced assembly or another instance of the same assembly?

The runtime will only load the assembly once (per appdomain). If it's
already loaded you'll get a reference back to the existing one.


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top