Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Type.GetType works when given partially qualified type name?

Tags:

In numerous places do I encounter partially qualified type names of the form FullTypeName, AssemblyName, i.e. like Type.AssemblyQualifiedName only without the version, culture and publicKeyToken qualifiers.

My question is how can one convert it to the respective Type in a minimum of effort? I thought that Type.GetType does the job, but alas, it does not. The following code, for instance, returns null:

Type.GetType("System.Net.Sockets.SocketException, System"); 

Of course, if I specify the fully qualified name it does work:

Type.GetType("System.Net.Sockets.SocketException, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); 

Thanks a lot.

like image 998
mark Avatar asked Mar 02 '10 23:03

mark


People also ask

What is fully qualified type name?

A fully qualified type name consists of an assembly name specification, a namespace specification, and a type name. Type name specifications are used by methods such as Type. GetType, Module. GetType, ModuleBuilder.

What is an assembly qualified name?

The assembly-qualified name of a type consists of the type name, including its namespace, followed by a comma, followed by the display name of the assembly. The display name of an assembly is obtained using the Assembly. FullName property.

How to Get type by name in C#?

To load a type by name, you either need it's full name (if the assembly has already been loaded into the appdomain) or its Assembly Qualified name. The full name is the type's name, including the namespace. You can get that by calling Type. GetType(typeof(System.


1 Answers

If the assembly has been loaded in the current domain then the code below usually works:

public static Type GetTypeEx(string fullTypeName) {     return Type.GetType(fullTypeName) ??            AppDomain.CurrentDomain.GetAssemblies()                     .Select(a => a.GetType(fullTypeName))                     .FirstOrDefault(t => t != null); } 

You can use it like so:

Type t = GetTypeEx("System.Net.Sockets.SocketException"); 
like image 78
dmihailescu Avatar answered Oct 05 '22 21:10

dmihailescu