Type.GetType

Hi!

Is there any way to find any type loaded into the runtime, regardless of which assembly it is available in I have the following situation (don't take this literally):

// Assembly1.dll

namespace Namespace1 {

   public class Class1 {

      public Type GetAType() {

         new Class2().FindType("Namespace1.Class1");

      }

   }

}

 

// Assembly2.dll

namespace Namespace1 {

   public class Class2 {

      public Type FindType(string typeName) {

         return Type.GetType(typeName);

      }

   }

}

This doesn't work, since Class1 is in Assembly1.dll and Class2 is in Assembly2.dll. Therefore, Type.GetType in Class2.FindType will only look in Assembly2.dll. It will not find Namespace1.Class1 there, since it is in Assembly1.dll.

Is there any nice and simple way of doing this

Thanks in advance,

Nille 



Answer this question

Type.GetType

  • jxxxs

    In that case, you need to explicitly load all assemblies you want to search for your type.

    This snippet searches the current directory for dll files, and tries to load them into the app domain:

     

    foreach (FileInfo fileInfo in new DirectoryInfo(".").GetFiles("*.dll"))

    {

        try

        {

            Assembly assembly = Assembly.LoadFile(fileInfo.FullName);

            AppDomain.CurrentDomain.Load(assembly.FullName);

        }

        catch (Exception)

        {

        }

    }



  • Kevin Welty

    Hi, and thanks for responding! This kind of almost worked.

    Consider a namespace N = { X, Y } (i.e. X and Y are types defined in the namespace N). If I explicitly reference X or Y, then the assembly will be loaded, as one might expect. However, if I don't reference X or Y, the assembly won't load, and thus AppDomain.CurrentDomain.GetAssemblies() won't return N.

    So, if I have an assembly MyAssembly.dll that consists of these classes:

    namespace ANamespace

    {

       public class Class1 { }

       public class Class2 { }

    }

    And another assembly:

    ...

    public static Type FindType(string name)

    {

       foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())

       {

          ...

       }

    }

    public static void Main(string[] args)

    {

       // This doesn't work...

       Type t = FindType("ANamespace.Class1");

        Class1 cls1 = new Class1();  // This causes MyAssembly.dll to get loaded

        t = FindType("ANamespace.Class1"); // This works

    }

    So, the problem is that the assembly isn't loaded unless a type in the assembly is referenced. Any simple way to get around this

    Regards, Andreas Nilsson


  • Alex Barnett - MSFT

    I haven't tried this, but the AppDomain class holds a list of all assemblies that are currently loaded:

    foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())

    {

        Type t = assembly.GetType(typeName, false);

        if (t != null) return t;

    }



  • Type.GetType