Delegates and methods

Asked

Viewed 436 times

6

When to use delegates?

Being that a delegate points to a method, it is not the same thing as creating a normal method?

  • What’s the difference and when to use and why to use?
  • It’s better?
  • Is worse?

2 answers

4


The delegate is assigned to a variable or passed as argument of a method (which will arrive in a variable), or as return. It is not possible to do this with a normal method (it even gives but not in the normal way and in a simpler way). So that is the reason to use it. It is useful when you need to treat a particular code as data, when you need to "store" the code in some variable.

And the variable term there is important, since you can exchange the data whenever you want, that is, you can change which code should be executed when this variable is executed (yes, in this case it is possible to call the variable, including passing arguments to it, exactly as it is done with a method).

So, as the name says, you’re 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 may determine what behaviour he wishes to give to a particular slot.

It is neither better, nor worse, it is different. When you need to "parameterize" which code to execute it is very useful. When you need to have a callback, very common in the use of events, for example. You can always do it another way, but with it it is easier.

A delegate is a special class that has a pointer to a code (may even be a common method) among other facilities. In C# o delegate need to have a signing and any (pointer to a) code that is stored on it must meet that signature.

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

See more in How to declare a function within 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 the 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 static void Main() {
        Exemplo teste = new Exemplo();
        teste.VerificaAlgo = new Func<bool>(() => ReadLine() == "teste");
        teste.FazAlgo();
    }
}

Behold working in the ideone. And in the *.NET Fiddle. Also put on the Github for future reference.

Other:

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

Use:

clientes.Ache(cliente => cliente.Nome.StartsWith("M"));

0

Events are of the type MulticastDelegate, a type of delegate invoking multiple functions.

Linq uses delegates to determine predicates.

Among other examples.

It is used when a type of custom processing is needed, without knowing in advance (at development time) what the function will accomplish. This can be assigned at runtime even by another Assembly, you reference System.Windows.Forms and assigns an Handler to a control event, for example. Without delegates it would be necessary to inherit the class and overwrite the methods, I think this is more a matter of personal taste, why it gives more or less the same work, is the concept of multi-paradigm language.

In addition, delegates can be assigned or cancelled, easily disabling some functionality without the need for conferences.

I particularly only use delegates when there is some multi-case processing, rather than writing a lot of if or switch and select the function in every run, you assign the function to the delegate and invoke it. And also to transmit signals between objects, mainly with competing operations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.