I want to invoke the method by the method name stored in the list. Can anyone help? I’m new to c#!
{
delegate string ConvertsIntToString(int i);
}
class Program
{
public static List<String> states = new List<string>() { "dfd","HiThere"};
static void Main(string[] args)
{
ConvertsIntToString someMethod = new ConvertsIntToString(states[1]);
string message = someMethod(5);
Console.WriteLine(message);
Console.ReadKey();
}
private static string HiThere(int i)
{
return "Hi there! #" + (i * 100);
}
}
It looks like you don’t need
Delegate.DynamicInvokeat all – you’re not trying to invoke it dynamically – you’re trying to create the delegate dynamically, which you can do withDelegate.CreateDelegate. Short but complete program based around your example (but without using a list – there’s no need for that here):Obviously you need to adjust it if the method you want is in a different type, or is an instance method, or is public.