It’s a little unclear whether you want to determine the type at runtime and define methods against it, or if you want to instantiate an already written type and call methods on it.
Fortunately, both options are possible.
The second scenario is more likely, so you need to look at the considerations (below), but note that it involves performance related fines (and small things like “what arguments does the method” become very important).
For the first scenario, you need to look at TypeBuilder , but it is much more complicated. Another option would be CSharpCodeProvider and dynamic assembly, but then again - non-trivial for any stretch.
using System; namespace MyNamespace { public class Foo { public void Bar() { Console.WriteLine("Foo.Bar called"); } } } class Program { static void Main() { string className = "MyNamespace.Foo, MyAssemblyName", methodName = "Bar"; Type type = Type.GetType(className); object obj = Activator.CreateInstance(type); type.GetMethod(methodName).Invoke(obj, null); } }
To include parameters (comments), you pass object[] instead of null :
using System; namespace MyNamespace { public class Foo { public void Bar(string value) { Console.WriteLine("Foo.Bar called: " + value); } } } class Program { static void Main() { string className = "MyNamespace.Foo, MyAssemblyName", methodName = "Bar"; Type type = Type.GetType(className); object obj = Activator.CreateInstance(type); object[] args = { "hello, world" }; type.GetMethod(methodName).Invoke(obj, args); } }
If you make this lot (for the same method), there is a way to improve performance using a typed delegate, but that does not bring you any special prizes.
source share