I just noticed kind of a bug in the function:
Type.GetType("System.Uri");
The return value is null whereas the following functions are working quite well...
Type.GetType("System.string");
Type.GetType("System.bool");
Type.GetType("System.DateTime");
...
Anyone knows, why the returned Type is null?
EDIT: removed Uri double entry...
The reason that Type.GetType("System.Uri")
returns null
is that the type is located in system.dll instead of mscorlib.dll. You must use the assembly-qualified name as noted above.
From MSDN:
typeName Type: System.String
The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.
I also hit this problem and realized that, especially in ASP.Net with JIT compilation, I do not always know the Assembly information. I added the following to my ReflectionUtilities class. It is a "sledgehammer to crack a nut" to some degree but it works with both the AssemblyQualifiedName and the basic class FullName. The first basically short-circuits the search of the CurrentDomainAssemblies that must otherwise occur.
public static Type FindType(string qualifiedTypeName)
{
Type t = Type.GetType(qualifiedTypeName);
if (t != null)
{
return t;
}
else
{
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
t = asm.GetType(qualifiedTypeName);
if (t != null)
return t;
}
return null;
}
}
Note: Given Reflection performance issues this should not be called inside loops without the assembly qualification if at all possible. Better to access the first item you need, extract the assembly information from that, and procede from there. Not always appropriate but much more efficient (if anything in Reflection can be called efficient:-)).
Alistair
try this code:
Uri uri = new Uri("http://test");
Type t = Type.GetType(uri.GetType().AssemblyQualifiedName);
and then u can copy/paste the AssemblyQualifiedName from the type
another method would be:
Type t = typeof(Uri);
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