Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I wanted to know if exists up a way to instantiate a class using a variable "myClass" and invoke a method and present a variable inside a variable always through. Example:
myClassName string;
metodName string;
string variableName;
For the class:
Assembly a = Assembly.Load ("MyLibrary");
Type t = a.GetType (MyLibrary.MyClass ");
object obj = Activator.CreateInstance (t);
For the method and variable?
t.xxxxxx (metodName)
t.xxxxxx (variableName)
thanks
Posted
Updated 29-Sep-10 7:30am
v2

Googling "c# instantiate class by name" would have led you here (as well as over 95,000 other results):

http://www.csharphelp.com/archives/archive200.html[^]
 
Share this answer
 
An object of class Type has a method InvokeMember. That is what you are looking for. Check out MSDN on how to use it.
 
Share this answer
 
How about using the Dynamic Language Runtime introduced in .Net 4.0?

That way you don't have to invoke anything to access members of an object whose type is unknown to the compiler.

Or ...

Have MyClass implement IMyPluginInterface - where the interface declares the members that should be exposed - then:

IMyPluginInterface someObject = (IMyPlugInInterface)Activator.CreateInstance("MyLibrary", "MyClass");
someObject.SomeMethod();
...
 
Share this answer
 
v2
What you are asking about is called "Reflection". The Activator as Chris posted will do exactly what you need and it is done by Reflection if you want to know more about the topic.
 
Share this answer
 
The easiest way to do this is to use Dynamic.

Internally .NET uses Reflection to invoke your member,just you dont need to do these calls
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900