Events and delegates questions

M

Manco

1. A delegate is a type-safe, object-oriented function pointer.

2. A delegate declartion is C-sharp, f.e., public delegate void
MyDelegate(int); defines a MulticastDelgate which contains a linked-list of
delegates that can be added using .Combine method.

3. An event object is an implementation of the Observer design pattern.

4. An event is declared thus:

public event MyDelegate MyEvent;

5. An event is simply a wrapper around a MulticastDelegate, the C-sharp
compiler will generate static += and -= operators to more easily add or
subtract MulticastDelegates to the underlying MulticastDelegate.
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi Manco,
1. A delegate is a type-safe, object-oriented function pointer.

Yes. Event more due to the multicast nature of the delegates.

2. A delegate declartion is C-sharp, f.e., public delegate void
MyDelegate(int); defines a MulticastDelgate which contains a linked-list
of delegates that can be added using .Combine method.

No. It declares a class that inherits from MulticastDelegate. This class
declares strongly typed Invoke and BeginInvoke methods

3. An event object is an implementation of the Observer design pattern.
Yes.


4. An event is declared thus:

public event MyDelegate MyEvent;

This is one of the possible declarations.
The other one is
public event MyDelegate MyEvent
{
add
{
....
}
remove
{
....
}
}

The former declares one private field of the type of the delagate +
declaration and implementation of the add and remove accessors. The
visiblity of the accessors is what is provided in the event declaration.
The latter doesn't declare the backup field. It gives you the oportunity to
provide your own implementation of the accessors.
5. An event is simply a wrapper around a MulticastDelegate, the C-sharp
compiler will generate static += and -= operators to more easily add or
subtract MulticastDelegates to the underlying MulticastDelegate.

No. Events are pair of methods *add* and *remove*. By the way docs specify
one more called invoke, but it is not supported by C#. Actually the names
could be any names since those names are provided in the assemply meta data,
but .NET specifications recomends tha the names of these accessors are named
after the name of the event, for example in the case of event MyEvent they
are named add_MyEent and remove_MyEvent.

+= and -= on the other hand are not overloded any where they are compiled by
the C# compiler in a special way. If on the right hand side stays delegate
or event name. The former is trianslated as Delegate.Combine and
Delegate.Remove respectively method calls; the latter is translated as
add_XXX and remove_XXX method calls.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top