Search code examples
c#reflectionmscorlib

Type from mscorlib not found


There is something I cannot understand. I can't read the type reference:

Assembly mscorlib = Assembly.Load("mscorlib");

// it DOES exist, returns type reference:
mscorlib.GetType("System.Deployment.Internal.Isolation.IDefinitionAppId");

// but its parent scope doesn't exist.. returns null:
mscorlib.GetType("System.Deployment.Internal.Isolation"); 

// even though it exists, it doesn't compile
// System.Deployment.Internal.Isolation.IDefinitionAppId x;

How is this possible?


Solution

  • The reason your last line won't compile is because IDefinitionAppId is internal - not because System.Deployment.Internal.Isolation is a type.

    Note that if Isolation were the name of a type, you'd have to use GetType("System.Deployment.Internal.Isolation+IDefinitionAppId") (note the +) as that's how nested types are represented in CLR names.

    It's very simple to demonstrate this:

    using System;
    using System.Reflection;
    
    public class Test
    {
        static void Main()
        {
            Assembly mscorlib = typeof(string).Assembly;
            string name = "System.Deployment.Internal.Isolation.IDefinitionAppId";
            Type type = mscorlib.GetType(name);
    
            // Prints System.Deployment.Internal.Isolation
            Console.WriteLine(type.Namespace);
        }
    }
    

    So System.Deployment.Internal.Isolation is a namespace, not a type, hence why Assembly.GetType(...) doesn't find it as a type.