Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different delegate uses

Tags:

c#

delegates

Possible Duplicate:
What is the difference between a delegate and events?

Possible Duplicate:
Difference between events and delegates and its respective applications

(copied from this duplicate)

When i have to raise an event i do this

public delegate void LogUserActivity(Guid orderGUID);
public event LogUserActivity ActivityLog;

even this works

public delegate void LogUserActivity(Guid orderGUID);
public LogUserActivity ActivityLog;

What is the difference between two of them

like image 470
Rohit Raghuvansi Avatar asked Jun 09 '26 12:06

Rohit Raghuvansi


1 Answers

There are three things here:

  • Declaring a delegate type
  • Creating a public variable of a delegate type
  • Creating a public event of a delegate type

The variable is just a normal variable - anyone can read from it, assign to it etc. An event only exposes subscribe/unsubscribe abilities to the outside world. A field-like event as you've shown here effectively has a "default" subscribe/unsubscribe behaviour, stored in a field with the same name. Within the declaring class, you access the field; outside you access the event.

I have an article about events and delegates which explains in more detail.

EDIT: To answer the comment, you can easily initialize a field-like event with a "no-op" handler:

public event LogUserActivity ActivityLog = delegate{};
like image 73
Jon Skeet Avatar answered Jun 12 '26 02:06

Jon Skeet