Dynamically invoking a constructor 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 constructor of a type in a referenced assembly.

Normally, if you have a direct reference to an assembly then you can simply initialise new objects using the ‘new’ keyword. In the absence of a direct reference this is not possible.

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;
	}
}

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.

Create a separate project in VS and make it a console app. Here’s how you load the assembly:

string pathToDomain = @"C:\pathToLib\Domain.dll";
Assembly domainAssembly = Assembly.LoadFrom(pathToDomain);

Next we get hold of the Customer type using its full name as follows:

Type customerType = domainAssembly.GetType("Domain.Customer");

We can locate the empty constructor of Customer in the following way:

Type[] emptyArgumentTypes = Type.EmptyTypes;
ConstructorInfo emptyConstructor = customerType.GetConstructor(emptyArgumentTypes);

You can learn more about ConstructorInfo here. In short it derives from MethodBase and it represents a Constructor which is a special type of method that returns an instance of a type. In the above code we specified that we wanted an empty constructor using an array of empty types. We can also locate the overloaded constructor by providing the type of the arguments list:

Type[] stringArgumentTypes = new Type[] { typeof(string) };
ConstructorInfo stringConstructor = customerType.GetConstructor(stringArgumentTypes);

You can invoke these constructors as follows:

object newEmptyCustomer = emptyConstructor.Invoke(new object[] { });
object newStringCustomer = stringConstructor.Invoke(new object[] { "Elvis" });

If step through this example with F11 then you’ll see that the Customer class appears in VS as the code reaches the constructor invocation examples.

View all posts on Reflection here.

Advertisement

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

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 )

Facebook photo

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

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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

%d bloggers like this: