12
What returns the instruction delegate { }
? Would be an empty delegate?
In which situations would it be necessary to create an empty delegate?
12
What returns the instruction delegate { }
? Would be an empty delegate?
In which situations would it be necessary to create an empty delegate?
12
What is a delegate
?
It’s roughly a pointer to a method, right? So what you have in it is an address to something that can be executed. This can be stored in variables. And this is the great advantage of the delegate
, you can vary what will be executed, since that variable can point at a time to a function, at another time to another function.
When you need to initialize the delegate
and
then we can assign to the delegate an empty function, ie that executes anything.
So the function is empty, the delegate is not, because it is the pointer. An empty delegate would actually be a null.
Additional references:
6
Just to complement the @Maniero response, where it’s used... I particularly use to start events not to 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);
}
}
Browser other questions tagged c# .net delegate
You are not signed in. Login or sign up in order to post.
With C# 6 you can also write something like
MeuEvento?.Invoke(null,null)
– Leandro Godoy Rosa