blah blah blah is here! blah blah » Close

up0down
link

Hi guys!
I have learned before, how to use reflection to call a method from another dll file, but I was wodering if it's possible to create an instance of a class in another dll through reflection?`?

last answered 2 years ago

1 answers

up0down
link

I know very little (see: nothing) about reflection, but I suppose you could call a method that creates an instance of a class :)

up0down
link

Thanks man, Of course!. :)

up0down
link

To create an instance of a type using reflection, check out the <a target="_new" href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx">Activator.CreateInstance</a> method.

up0down
link

Ok now, I can't see how that method knows which assembly I'm trying to connect to. Or which namespace. ??

up0down
link

OK, here's a quick example.
Suppose you have this dll (test.dll say):
using System;
namespace Test
{
public class MyClass
{
public void MyMethod()
{
Console.WriteLine("Hello from Test.MyClass!");
}
}
}
and you want to create an instance of Test.MyClass and then call MyMethod() from another program using reflection.
Here's how to do it (I've used Assembly.CreateInstance rather than Activator.CreateInstance here):
using System;
using System.Reflection;
namespace Program
{
class MyProgram
{
static void Main()
{
Assembly assembly = Assembly.LoadFrom("test.dll");
object mc = assembly.CreateInstance("Test.MyClass");
Type t = mc.GetType();
MethodInfo mi = t.GetMethod("MyMethod");
mi.Invoke(mc, null);
Console.ReadKey();
}
}
}

This post was imported from csharpfriends, if you have a similiar question please ask it again.

All previous members have been migrated, hope you enjoy the new platform!

Feedback