to understand the differences you can look at this 2 examples
Exemple with Delegates (Action in this case that is a kind of delegate that doen't return value)
public class Animal
{
public Action Run {get; set;}
public void RaiseEvent()
{
if (Run != null)
{
Run();
}
}
}
to use the delegate you should do something like this
Animale animal= new Animal();
animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running") ;
animal.RaiseEvent();
this code works well but you could have some weak spots.
For example if I write this
animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running");
animal.Run = () => Console.WriteLine("I'm sleeping") ;
with the last line of code I had override the previous behaviors just with one missing +
(I have used +
instead of +=
)
Another weak spot is that every class that use your Animal
class can raise RaiseEvent
just calling it animal.RaiseEvent()
.
To avoid this weak spots you can use events
in c#.
Your Animal class will change in this way
public class ArgsSpecial :EventArgs
{
public ArgsSpecial (string val)
{
Operation=val;
}
public string Operation {get; set;}
}
public class Animal
{
public event EventHandler<ArgsSpecial> Run = delegate{} //empty delegate. In this way you are sure that value is always != null because no one outside of the class can change it
public void RaiseEvent()
{
Run(this, new ArgsSpecial("Run faster"));
}
}
to call events
Animale animal= new Animal();
animal.Run += (sender, e) => Console.WriteLine("I'm running. My value is {0}", e.Operation);
animal.RaiseEvent();
Differences:
- You aren't using a public property but a public field (with events the compiler protect your fields from unwanted access)
- Events can't directly be assigned. In this case you can't do the previous error that I have showed with overriding the behavior.
- No one outside of your class can raise the event.
- Events can be included in an interface declaration, whereas a field cannot
notes
EventHandler is declared as the following delegate:
public delegate void EventHandler (object sender, EventArgs e)
it takes a sender (of Object type) and event arguments. The sender is null if it comes from static methods.
You can use also EventHAndler
instead this example that use EventHandler<ArgsSpecial>
refer here for documentation about EventHandler