run a method with reflection in csharp

To run a method with reflection in C#, you need to get a Type object that represents the type of the class that owns the method. You can then use this Type object to get a MethodInfo object that represents the method you want to run. Finally, you can use the Invoke method on the MethodInfo object to run the method.

Here's an example:

main.cs
// assume MyClass has a method named MyMethod that takes no parameters and returns void
object obj = new MyClass();
Type type = obj.GetType();
MethodInfo methodInfo = type.GetMethod("MyMethod");
methodInfo.Invoke(obj, null);
225 chars
6 lines

In this example, we first create an instance of the MyClass object. We then use the GetType method to get a Type object that represents the class. We use the GetMethod method of the Type object to get a MethodInfo object that represents the MyMethod method. Finally, we use the Invoke method of the MethodInfo object to run the method on the MyClass instance that we created. Note that since MyMethod takes no parameters, we pass null for the second argument to the Invoke method. If the method had parameters, we would pass an array of objects that represents the parameter values.

gistlibby LogSnag