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.
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With