event

  • Thread starter Thread starter BC
  • Start date Start date
B

BC

Hi all,

Just wondering what are the difference between:

public event EventHandler MessageNotify;
public EventHandler MessageNotify;

A friend told me it's related to the accessibility levels.


Cheers,

Benny
 
BC said:
Hi all,

Just wondering what are the difference between:

public event EventHandler MessageNotify;
public EventHandler MessageNotify;

A friend told me it's related to the accessibility levels.

The only difference I could see was that it changed the icon to lightening
bolt but I'm sure there's more to it than that. I know that you don't
strictly need the event keyword.

Michael
 
Michael C said:
The only difference I could see was that it changed the icon to lightening
bolt but I'm sure there's more to it than that. I know that you don't
strictly need the event keyword.

You do if you want an event, not a delegate field.

The difference in the two is that when you use event, you are actually
creating an event property, which, like regular properties, is actually a
collection of methods used to access the event. C# uses 2, add and remove,
which permit clients to add or remove a delegate from the event. An event
field offers none of that and allows anyone with an instance of the class to
raise, add, remove, or do anything else to the delegate they wish.

So, accessibility is close, but not quite right. A public event is still
public, the event simply does not offer direct access to the delegate.
 
Daniel O'Connell said:
You do if you want an event, not a delegate field.

The difference in the two is that when you use event, you are actually
creating an event property, which, like regular properties, is actually a
collection of methods used to access the event. C# uses 2, add and remove,
which permit clients to add or remove a delegate from the event. An event
field offers none of that and allows anyone with an instance of the class
to raise, add, remove, or do anything else to the delegate they wish.

I forgot to mention a couple things. One is that when you use write events
using the standard syntax, the compiler genereates the property and a
backing field and treats code calling the event internally like its refering
to the private field.

The other is that you can write your own event properties, although its
probably one of the least well known features in C#(along with stackalloc):
public event EventHandler MessageNotify
{
add
{
//add the delegate to your delegate collection(usually using
Delegate.Combine())
}
remove
{
//remove the delegate from your delegate collection(usually using
Delegate.Remove())
}
}
 
The other is that you can write your own event properties, although its
probably one of the least well known features in C#

Yes, which is a pity when the default behaviour is nasty (locking on
"this")...
(along with stackalloc):

Ooh, I hadn't seen that before. Interesting...
 
Back
Top