Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Create Instance or invoke members of a class from a loaded assembly

Create Instance or invoke members of a class from a loaded assembly

Scheduled Pinned Locked Moved C#
debugginghelptutorialquestion
6 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    Danzy83
    wrote on last edited by
    #1

    I have classes in an assembly that I have been able to load using Assembly.LoadFrom() method. I now need to call a method in a class from the loaded assembly but I don't know how to do that. I tried the following:

    Assembly asm = Assembly.LoadFrom("LibTry.dll");

    if (asm != null)
    {
    object obj = asm.CreateInstance("LibTry.Try");
    Type[] types = asm.GetExportedTypes();

       // I now need to invoke a method from the class for further processing.
    

    }

    I'm able to create an instance of a class in the assembly and the return value in 'obj' is valid and not null. By running the debugger, I set a breakpoint at the line

    Type[] types = asm.GetExportedTypes();

    I hovered the mouse over the return values and I saw the name of the class in the 'obj' and the exported types in 'types'. The problem now is to make function calls from the class. Is there any way I can create an instance of the exported types using the name of the class rather than 'object' or call and use the public members in the class? Please help and thanks in advance.

    L J B 3 Replies Last reply
    0
    • D Danzy83

      I have classes in an assembly that I have been able to load using Assembly.LoadFrom() method. I now need to call a method in a class from the loaded assembly but I don't know how to do that. I tried the following:

      Assembly asm = Assembly.LoadFrom("LibTry.dll");

      if (asm != null)
      {
      object obj = asm.CreateInstance("LibTry.Try");
      Type[] types = asm.GetExportedTypes();

         // I now need to invoke a method from the class for further processing.
      

      }

      I'm able to create an instance of a class in the assembly and the return value in 'obj' is valid and not null. By running the debugger, I set a breakpoint at the line

      Type[] types = asm.GetExportedTypes();

      I hovered the mouse over the return values and I saw the name of the class in the 'obj' and the exported types in 'types'. The problem now is to make function calls from the class. Is there any way I can create an instance of the exported types using the name of the class rather than 'object' or call and use the public members in the class? Please help and thanks in advance.

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      Use the GetMethod member from the Type, similar to the code below;

      namespace bla
      {
      public class X
      {
      public void Test(string what)
      {
      Console.WriteLine(what);
      }
      }
      class Program
      {
      static void Main(string[] args)
      {
      Assembly asm = Assembly.GetExecutingAssembly();
      if (asm != null)
      {
      object obj = asm.CreateInstance("bla.X");
      //Type[] types = asm.GetExportedTypes(); // why load all types if you need only one?
      Type xType = obj.GetType();

                  // I now need to invoke a method from the class for further processing.
                  MethodInfo mi = xType.GetMethod("Test"); // get the method from the type
                  mi.Invoke(obj, new object\[\] { "Hello World" }); // invoke it on the object
              } 
              Console.ReadKey(); 
          } 
      }
      

      }

      Bastard Programmer from Hell :suss: if you can't read my code, try converting it here[^]

      D 1 Reply Last reply
      0
      • L Lost User

        Use the GetMethod member from the Type, similar to the code below;

        namespace bla
        {
        public class X
        {
        public void Test(string what)
        {
        Console.WriteLine(what);
        }
        }
        class Program
        {
        static void Main(string[] args)
        {
        Assembly asm = Assembly.GetExecutingAssembly();
        if (asm != null)
        {
        object obj = asm.CreateInstance("bla.X");
        //Type[] types = asm.GetExportedTypes(); // why load all types if you need only one?
        Type xType = obj.GetType();

                    // I now need to invoke a method from the class for further processing.
                    MethodInfo mi = xType.GetMethod("Test"); // get the method from the type
                    mi.Invoke(obj, new object\[\] { "Hello World" }); // invoke it on the object
                } 
                Console.ReadKey(); 
            } 
        }
        

        }

        Bastard Programmer from Hell :suss: if you can't read my code, try converting it here[^]

        D Offline
        D Offline
        Danzy83
        wrote on last edited by
        #3

        Thanks Eddy! It's working now. I hope it works for fields as well. I will try that soon.

        L 1 Reply Last reply
        0
        • D Danzy83

          Thanks Eddy! It's working now. I hope it works for fields as well. I will try that soon.

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          You're welcome, and it does, using the [GetField](http://msdn.microsoft.com/en-us/library/53seyfee.aspx)[[^](http://msdn.microsoft.com/en-us/library/53seyfee.aspx "New Window")] method, also found on the objects' type. It'll return a [FieldInfo](http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.aspx)[[^](http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.aspx "New Window")] variable over which you can access it's content, or fetch it's attributes.

          Bastard Programmer from Hell :suss: if you can't read my code, try converting it here[^]

          1 Reply Last reply
          0
          • D Danzy83

            I have classes in an assembly that I have been able to load using Assembly.LoadFrom() method. I now need to call a method in a class from the loaded assembly but I don't know how to do that. I tried the following:

            Assembly asm = Assembly.LoadFrom("LibTry.dll");

            if (asm != null)
            {
            object obj = asm.CreateInstance("LibTry.Try");
            Type[] types = asm.GetExportedTypes();

               // I now need to invoke a method from the class for further processing.
            

            }

            I'm able to create an instance of a class in the assembly and the return value in 'obj' is valid and not null. By running the debugger, I set a breakpoint at the line

            Type[] types = asm.GetExportedTypes();

            I hovered the mouse over the return values and I saw the name of the class in the 'obj' and the exported types in 'types'. The problem now is to make function calls from the class. Is there any way I can create an instance of the exported types using the name of the class rather than 'object' or call and use the public members in the class? Please help and thanks in advance.

            J Offline
            J Offline
            jschell
            wrote on last edited by
            #5

            Dan_K wrote:

            The problem now is to make function calls from the class

            You could use an interface.

            1 Reply Last reply
            0
            • D Danzy83

              I have classes in an assembly that I have been able to load using Assembly.LoadFrom() method. I now need to call a method in a class from the loaded assembly but I don't know how to do that. I tried the following:

              Assembly asm = Assembly.LoadFrom("LibTry.dll");

              if (asm != null)
              {
              object obj = asm.CreateInstance("LibTry.Try");
              Type[] types = asm.GetExportedTypes();

                 // I now need to invoke a method from the class for further processing.
              

              }

              I'm able to create an instance of a class in the assembly and the return value in 'obj' is valid and not null. By running the debugger, I set a breakpoint at the line

              Type[] types = asm.GetExportedTypes();

              I hovered the mouse over the return values and I saw the name of the class in the 'obj' and the exported types in 'types'. The problem now is to make function calls from the class. Is there any way I can create an instance of the exported types using the name of the class rather than 'object' or call and use the public members in the class? Please help and thanks in advance.

              B Offline
              B Offline
              BobJanova
              wrote on last edited by
              #6

              You can use the reflection API to call methods, properties and fields of any class, including those that you've loaded from an assembly at runtime. This is what Eddy's pointed you at. However, reflection is slow, and also pretty cumbersome to write code for. If you know what methods you want to call, then that means you can define an interface, and if you're writing the assembly you're trying to load from (or people are writing them to an API you specify), you can make sure the class you try to load implements it. Put that interface in a library that both the main application and the external library can refer to (this can be actually in the application assembly in some cases), and make sure that the classes you want to interact with in the external assembly implement it. You can then cast the result of Activator.CreateInstance to the interface and call methods on the instance directly. There are several examples of plugin architectures (because that's what your close to) available on CP. Here's a simple example modified from a previous version of my LobbyClient (the current one loads plugins into a separate AppDomain which you probably aren't looking for):

              public static IGameType LoadContent(String filename){
              Assembly a = Assembly.LoadFrom(filename);
              if(a == null) throw new GameLoadException("Assembly "+filename+" not found or not valid");
              foreach(Module mod in a.GetLoadedModules()){
              foreach(Type ty in mod.GetTypes()){
              foreach(Type intf in ty.GetInterfaces()){
              if(intf == typeof(IGameType)){
              return (IGameType)System.Activator.CreateInstance(ty);
              }
              }
              }
              }
              }

              IGameType is specified somewhere that plugin classes can see it when you're writing plugins.

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups