Monday, January 16, 2017

Difference Between delegate (Multicast Delegate) and event

1. Events can be included in an interface declaration, whereas a field cannot.
2. Events can't directly be assigned. While delegate object can be assign directly means it is chance that you override  the previous assign method.
Example 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#.

3. You aren't using a public property but a public field (with events the compiler protect your fields from unwanted access)

4. No one outside of your class can raise the event.

No comments:

Followers

Link