Dynamically invoking a method with Reflection in .NET C#

Say you do not have access to a .NET assembly at compile time but you want to run code in it. It’s possible to dynamically load an assembly and run code in it without early access.

Here we’ll see how to invoke a method of a type in a referenced assembly.

Open Visual Studio 2012/2013 and create a new C# class library project called Domain. Add the following Customer class to it:

public class Customer
{
	private string _name;

	public Customer() : this("N/A")
	{}

	public Customer(string name)
	{
		_name = name;
	}

        public void DoVoidMethod(int intParameter, string stringParameter)
	{
		Console.WriteLine("Within Customer.DoVoidMethod. Parameters: {0}, {1}", intParameter, stringParameter);
	}

	public int DoRetMethod(int intParameter)
	{
		return intParameter + 1;
	}
}

Build the solution and locate the compiled Domain.dll library. It should be located in either the Debug or Release folder within the bin folder depending on the compilation configuration in VS. Copy the .dll and put it somewhere else on your main drive where you can easily find it. We’re pretending that you got the library from another source but you for whatever reason cannot reference it at compile time. E.g. the source is loaded into your app as a plugin which follows some naming conventions so that your code can unwrap it and invoke its code.

In this post we saw how to invoke a constructor so we won’t go into that again. Once you have an instance of the object then you can use the Type object to find the available methods, properties, events etc. of that type: MethodInfo, EventInfo, PropertyInfo etc.

Let’s see how we can get hold of the void method. First we’ll invoke the overloaded constructor:

string pathToDomain = @"C:\Studies\Reflection\Domain.dll";
Assembly domainAssembly = Assembly.LoadFrom(pathToDomain);
Type customerType = domainAssembly.GetType("Domain.Customer");
Type[] stringArgumentTypes = new Type[] { typeof(string) };
ConstructorInfo stringConstructor = customerType.GetConstructor(stringArgumentTypes);
object newStringCustomer = stringConstructor.Invoke(new object[] { "Elvis" });

Then we locate the DoVoidMethod method and invoke it on the newStringCustomer object. We also provide an object array to represent the arguments to the method.

MethodInfo voidMethodInfo = customerType.GetMethod("DoVoidMethod");
voidMethodInfo.Invoke(newStringCustomer, new object[] { 3, "hello" });

If you run this code then a Console window should pop up with the message “Within Customer.DoVoidMethod. Parameters: 3, hello” on it.

Next we’ll invoke the DoRetMethod method and read its return value:

MethodInfo retMethodInfo = customerType.GetMethod("DoRetMethod");
int returnValue = Convert.ToInt32(retMethodInfo.Invoke(newStringCustomer, new object[] { 4 }));

The returnValue variable will be 5 as expected.

View all posts on Reflection here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Dynamically invoking a method with Reflection in .NET C#

  1. Brent says:

    Hey Andras.

    What’s a good practical example of when this would be helpful?

    Is this for cases when the domain.dll doesn’t provide any public interface into it’s implementation?

    • Andras Nemes says:

      Hi Brent,

      Think of a pluggable architecture. Suppose you have a website or some other software that other programmers can develop plugins for. Usually such plugins must conform to some conventions, e.g. have a class that implements a specific interface, has a method called “run” etc. The plugin, i.e. the dll file can be deployed in folder which your application monitors. The plugin dll can then be checked, analysed and executed through reflection.

      Do you know the continuous integration tool called TeamCity? It has an extremely pluggable architecture which allows programmers to write their own tools for different parts of the application. TeamCity has a special folder where custom plugins can be deployed. TeamCity then reads the contents of the plugin – I’m not sure exactly how TC does this but a good guess is reflection.

      //Andras

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: