Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetType not working [duplicate]

Tags:

c#

types

uri

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...

like image 962
Daffi Avatar asked Oct 15 '12 14:10

Daffi


3 Answers

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.

like image 59
theMayer Avatar answered Oct 12 '22 23:10

theMayer


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

like image 38
Alistair Gillanders Avatar answered Oct 12 '22 22:10

Alistair Gillanders


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);
like image 35
x4rf41 Avatar answered Oct 12 '22 22:10

x4rf41