c# – C # How to save a method in a variable to be called later?

Question:

I have the following method in a C # class

void Mimetodo(string parametro1, string parametro2)
{
   // Código del metodo
}

void Mimetodo2(int parametro1)
{
   // Código del metodo
}

and now what I want is to match that method to a variable to make a call later for example something like this:

va = Mimetodo("5", "4");
vb = Mimetodo2(3);
if (opcion == "1") v = vb;
if (opcion == "2") v = va;
v; // Esto seria una llamada a la función que toca.

In other words, I want to save the reference to the call of that function.

Answer:

One option is to use the Action delegate, which allows you to encapsulate a method.

Action<string, string> funcion = MimeTodo;
            
funcion("hola", "mundo"); // Esta es la llamada a la función MimeTodo con los parámetros especificados

However, you will still have to pass the parameters to the Action instance.

To avoid this, we can use a lambda expression.

Action funcion = () => MimeTodo("hola", "mundo");

funcion(); // Esta es la llamada a la función lambda, que a su vez ejecuta el método MimeTodo
Scroll to Top