Reputation: 37
As I understand an Event is a way for a class to allow clients to give it delegates to methods that should be called when the event occurs. When the event occurs, the delegate(s) given to it by its clients are invoked.
But as demonstrated in following code above said functionality can also be achieved by delegate only i.e. without using delegate.
class Program
{
static void Main(string[] args)
{
ListWithChangedEvent lwce = new ListWithChangedEvent();
lwce.delegateVariable = DelegateTestMethod;
lwce.Add("test");
Console.ReadLine();
}
public static void DelegateTestMethod(object sender, object e)
{
}
}
public delegate void ChangedEventHandler(object sender, object e);
public class ListWithChangedEvent : System.Collections.ArrayList
{
public override int Add(object value)
{
int result = base.Add(value);
if (delegateVariable != null)
delegateVariable(this, "");
return result;
}
public ChangedEventHandler delegateVariable;
}
So, I was wondering what additional functionality does Events provide?
Upvotes: 1
Views: 662
Reputation: 148524
event is just the access approach
to the handler.
it wont allow you to do myHandler=myFunc;
only using +=
( from outer class)
it was made that if another dumb use your code - so he wont destroy your chain by using =
so you allow him only +=
or -=
Upvotes: 0
Reputation: 564403
So, I was wondering what additional functionality does Events provide?
Events provide two distinctly different advantages over exposing a public delegate:
Upvotes: 5
Reputation: 38825
Your example allows for a single delegate to be called. The event
is a collection of delegates, meaning you can +=
and -=
your heart away (even during event invocation).
Upvotes: 0