Reflection and Constructors

V

V. Jenks

I am using reflection to load classes and I can't find any
examples on how to pass values to constructor parameters
using reflection, how is this done?

Here's an example of one of my methods, as you can see it
accepts two parameters. I want to pass those two values to
the constructor of the class I'm loading via reflection.

public IDbAdapter CreateAdapter(string query,
IDbConnection onnection)
{
string dbType = DB_ASSEMBLY;
string dbAdapterClass = Config.DbAdapterClass;

//load the assembly and class
IDbAdapter da =
(IDbAdapter)Assembly.Load(assemblyName).CreateInstance(className);

return da;
}

Thanks in advance!
 
J

Jon Skeet [C# MVP]

V. Jenks said:
I am using reflection to load classes and I can't find any
examples on how to pass values to constructor parameters
using reflection, how is this done?

Either use Activator.CreateInstance (Type, object[]) or from the Type
reference, find the constructor you want (using Type.GetConstructor)
and then call Invoke on it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top