Empty delegate (delegate {})

9

What does the delegate { } statement return? Would you be an empty delegate?

In what situations would it be necessary to create an empty delegate?

    
asked by anonymous 13.12.2016 / 01:17

2 answers

9

What is a delegate ? Roughly it's a pointer to a method, right? So what you will have in it is an address for something that can be executed. This can be saved in variables. And this is the great advantage of delegate , you can vary what will be executed, since that variable can point at one time to one function, at another time to another function.

When you need to initialize delegate and

  • You do not want to still give it a useful function and leave it for later,
  • or you want the function to be "do nothing",

Then we can assign the delegate an empty function, that is, it performs nothing.

Then the function is empty, the delegate does not, because it is the pointer. An empty delegate would actually be a null.

Additional references:

13.12.2016 / 01:32
5

Just to complement the @bigown response, where it is used ... I particularly use to start events so I do not worry if the event is null

For example:

public class Teste{

  public event EventHandler MeuEvento;
  public event EventHandler MeuEvento2 = delegate { };

  public void MetodoExemplo(){

      //se quiser disparar o evento deve-se antes checar se alguem se registrou, 
     if (MeuEvento != null)
         MeuEvento(null,null);

     //agora como iniciamos o event não precisamos se "preocupar"
     MeuEvento2 (null,null);
  }
}
    
13.12.2016 / 11:16