Delegates and methods

3

When to use delegates . If I have a delegate I point to a correct method? Would not it be the same as creating a normal method? What's the difference and when to use and why to use? Is better? Is it worse?

    
asked by anonymous 02.03.2016 / 03:32

1 answer

3

The delegate is assigned to a variable or passed as an argument to a method, or as a return. You can not do this with a normal method. So that's the reason to use it. It is useful when you need to treat a particular code as a given, when you need to "store" the code in some variable.

And the variable term there is important, since you can change the data when you want, that is, you can change what is the code that should be executed when this variable is executed (yes, in this case it is possible to call the variable, inclusive passing arguments to it, just like you do with a method).

Then, as the name says, you are delegating the execution to some code to be determined. In a way we can say that it is a virtual method defined at runtime. It gives a lot of flexibility to the object that uses this feature. The consumer of the object can determine what behavior it wants to give to a particular slot .

It's neither better nor worse, it's different. When you need to "parameterize" what code to run it is very useful. When you need to have a callback function, very common in using events , for example . You can always do it another way, but with it it's easier.

A delegate is a special class that has a pointer to a code (may even be a common method). In C # the delegate needs to have a specific signature and any (pointer to a) that is stored on it must fulfill this signature.

delegate is a type that can be declared for later use, but can also use some predefined ones that will be parametrized .

See more in How to declare a function inside another function in C #? , What is the difference between a lambda expression, a closure, and a delegate? and When and where to use a delegate in C #? .

Example:

class Exemplo {
    public Func<bool> VerificaAlgo { get; set; }
    public void FazAlgo() {
        if (VerificaAlgo()) {
            WriteLine("é apenas um teste");
        } else {
            WriteLine("a coisa é séria");
        }
    }
}

class Program {
    public void Main() {
        Exemplo teste = new Exemplo();
        teste.VerificaAlgo = new Func<bool>(() => Console.ReadLine() == "teste");
        teste.Fazalgo();
    }
}

Other:

public Cliente Ache(Predicate<Customer> condicao) {
    foreach (var cliente in lista.Clientes)
       if (condicao(cliente))
          return cliente;
}

Usage:

clientes.Ache(cliente => cliente.Nome.StartsWith("M"));
    
02.03.2016 / 04:15