473,511 Members | 15,581 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Learning delegates and events

Hi,

I am new to C# and want to create my own events within a console app.
However I am struggling mentally with this, and have looked at the MSDN
documentation but I am drawing a blank. Is there anywhere on the net
that shows a very basic delegate and a very basic event? Some nice
simple example code is what I'm looking for with no fluff around it.

Thanks!

--
Mark Allison, SQL Server MVP
http://www.markallison.co.uk

Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602m.html
Nov 16 '05 #1
14 1446
I will definitely post a simple article on both today but, in the
meanwhile, I am quite sure you should find this helpful.

The delegate is a type which is capable of encapsulating a method
signature. The delegate can be used in conjunction with events. An event
is a type that is usually declared inside the class.
public class MyClass
{
// The delegate that points to the method to invoke. The
// method's return type in this case is 'void'.
public delegate void MyDelegate();
// If the method that is going to handle the event
// (MyMethod in this case) takes parameters, declare
// the delegate as follows
public delegate void MyDelegate(int i);
// The event is of type MyDelegate
public event MyDelegate MyEvent;
public MyClass()
{
// Attach the event to the delegate
this.MyEvent+=new MyDelegate(MyMethod);
}
// This is the method that acts as the event procedure.
public void MyMethod()
{
// Handle the event here.
}
}

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #2
Thanks,

OK, let me put this into my own words, and then you can slap me down. ;-)

You create a delegate called public delegate void MyDelegate(int i) -
this delegate runs code with the same sig. Cool, got that.

You then define your event as follows:
public event MyDelegate MyEvent;

I don't acutally understand the above line of code. What is that
effectively declaring?

When you attach the event to the delegate are you "firing the event",
raising the event? I want the event to be listened to from another class
altogether from this one. How do I get that other class to listen to
events in this class?

I'm sorry but your very simple example just confused me even more.
--
Mark Allison, SQL Server MVP
http://www.markallison.co.uk

Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602m.html
Ravichandran J.V. wrote:
I will definitely post a simple article on both today but, in the
meanwhile, I am quite sure you should find this helpful.

The delegate is a type which is capable of encapsulating a method
signature. The delegate can be used in conjunction with events. An event
is a type that is usually declared inside the class.
public class MyClass
{
// The delegate that points to the method to invoke. The
// method's return type in this case is 'void'.
public delegate void MyDelegate();
// If the method that is going to handle the event
// (MyMethod in this case) takes parameters, declare
// the delegate as follows
public delegate void MyDelegate(int i);
// The event is of type MyDelegate
public event MyDelegate MyEvent;
public MyClass()
{
// Attach the event to the delegate
this.MyEvent+=new MyDelegate(MyMethod);
}
// This is the method that acts as the event procedure.
public void MyMethod()
{
// Handle the event here.
}
}

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #3
Ravichandran,

I just found this article, looks quite good.
http://www.codeproject.com/csharp/De...sAndEvents.asp

I will let you know if I'm still confused after reading that - I'm
following it so far! You see, I have a VB background, so learning how to
program properly is a bit of a steep curve! :-)

--
Mark Allison, SQL Server MVP
http://www.markallison.co.uk

Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602m.html
Ravichandran J.V. wrote:
I will definitely post a simple article on both today but, in the
meanwhile, I am quite sure you should find this helpful.

The delegate is a type which is capable of encapsulating a method
signature. The delegate can be used in conjunction with events. An event
is a type that is usually declared inside the class.
public class MyClass
{
// The delegate that points to the method to invoke. The
// method's return type in this case is 'void'.
public delegate void MyDelegate();
// If the method that is going to handle the event
// (MyMethod in this case) takes parameters, declare
// the delegate as follows
public delegate void MyDelegate(int i);
// The event is of type MyDelegate
public event MyDelegate MyEvent;
public MyClass()
{
// Attach the event to the delegate
this.MyEvent+=new MyDelegate(MyMethod);
}
// This is the method that acts as the event procedure.
public void MyMethod()
{
// Handle the event here.
}
}

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #4
Mark Allison <ma***@no.tinned.meat.mvps.org> wrote:
OK, let me put this into my own words, and then you can slap me down. ;-)

You create a delegate called public delegate void MyDelegate(int i) -
this delegate runs code with the same sig. Cool, got that.

You then define your event as follows:
public event MyDelegate MyEvent;

I don't acutally understand the above line of code. What is that
effectively declaring?
It's effectively declaring a field, an event and two operations on the
event. An event has add/remove operations, each of which take a
compatible delegate instance as their parameter. The C# compiler adds
these in by default if you don't specify them. The exact naming and
semantics are unfortunately not defined in the specification, but it's
something like:

public event SomeDelegate Name;

translates to

// This is what stores the actual invocation list.
private SomeDelegate _Name;

// This is the public side of things
public event SomeDelegate Name
{
add
{
lock (this)
{
_Name += value;
}
}
remove
{
lock (this)
{
_Name -= value;
}
}
}

See http://www.pobox.com/~skeet/csharp/t...ckchoice.shtml for a
more thread-safe version.
When you attach the event to the delegate are you "firing the event",
raising the event?
No, you're subscribing to the event.
I want the event to be listened to from another class
altogether from this one. How do I get that other class to listen to
events in this class?


Here's a two-class (plus delegate definition) example:

using System;

delegate void TestDelegate();

class EventHolder
{
public event TestDelegate Foo;

public void RaiseEvent()
{
if (Foo != null)
{
Foo();
}
}
}

class Client
{
static void Main()
{
EventHolder holder = new EventHolder();

holder.Foo += new TestDelegate(First);
holder.Foo += new TestDelegate(Second);

holder.RaiseEvent();
}

static void First()
{
Console.WriteLine("First");
}

static void Second()
{
Console.WriteLine("Second");
}
}
Note that the event delegate ends up as a multicast delegate (I think
single cast delegates are effectively obsolete) so you can effectively
make one delegate out of lots - it just ends up calling them all in
turn.

I was confused for a while as to what the difference between a delegate
and an event was - and basically it's an encapsulation issue. An event
really just encapsulates adding and removing delegates (handlers). A
delegates itself has that and the ability to be fired. Note that from
Client I couldn't have called holder.Foo() directly - I can only add
and remove delegates. Similarly, events can be implemented without a
straight delegate member variable - some classes may have hundreds of
potential events, most of which aren't subscribed to by anything. In
that case, it makes sense to have some other data structure (eg a list
of events which *have* been subscribed to). The event encapsulation
allows that to happen.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
Jon Skeet [C# MVP] <sk***@pobox.com> wrote:
It's effectively declaring a field, an event and two operations on the
event. An event has add/remove operations, each of which take a
compatible delegate instance as their parameter.


<snip>

Oops - something I meant to add: the C# compiler doesn't use the
"raise" operation on an event, but that's another operation the CLI
defines.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
On Tue, 21 Sep 2004 11:29:04 +0100, Mark Allison wrote:
I want the event to be listened to from another class
altogether from this one. How do I get that other class to listen to
events in this class?


Does the following help?

using System;

public class EventRaiser
{
public void RaiseEvent() {
DemoEvent(123);
}

public event DemoEventHandler DemoEvent;
}

public delegate void DemoEventHandler(int n);

public class EventSubscriber
{
EventRaiser eventRaiser;

public void SubscribeToAndRaiseEvent() {
eventRaiser = new EventRaiser();
eventRaiser.DemoEvent += new DemoEventHandler(raiser_DemoEvent);

eventRaiser.RaiseEvent();
}

void raiser_DemoEvent(int n) {
Console.WriteLine(String.Format("In raiser_DemoEvent. n = {0}.", n));
}
}

public class ProgramEntryPoint
{
static void Main() {
EventSubscriber subscriber = new EventSubscriber();
subscriber.SubscribeToAndRaiseEvent();

Console.Read();
}
}

--
http://tomjb.com/blog/
Nov 16 '05 #7
Thanks Thomas,

What I don't understand is that the Client Raised the event. I want the
Client to subscribe to the event and listen to see if anything
interesting happens in EventRaiser.

Let me describe my scenario. I have a class which I would like to raise
events from, these events need to pass a string. I have another class
which will listen for these events, and then print the string to the
Console using Console.WriteLine.

How would I do that? I don't want the subscribing class to raise the
event, I want it to react to an event, i.e. listen to an event.

Am I missing something here? Is it all in the semantics? I'm still not
getting it...

--
Mark Allison, SQL Server MVP
http://www.markallison.co.uk

Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602m.html
Thomas Edison wrote:
On Tue, 21 Sep 2004 11:29:04 +0100, Mark Allison wrote:

I want the event to be listened to from another class
altogether from this one. How do I get that other class to listen to
events in this class?

Does the following help?

using System;

public class EventRaiser
{
public void RaiseEvent() {
DemoEvent(123);
}

public event DemoEventHandler DemoEvent;
}

public delegate void DemoEventHandler(int n);

public class EventSubscriber
{
EventRaiser eventRaiser;

public void SubscribeToAndRaiseEvent() {
eventRaiser = new EventRaiser();
eventRaiser.DemoEvent += new DemoEventHandler(raiser_DemoEvent);

eventRaiser.RaiseEvent();
}

void raiser_DemoEvent(int n) {
Console.WriteLine(String.Format("In raiser_DemoEvent. n = {0}.", n));
}
}

public class ProgramEntryPoint
{
static void Main() {
EventSubscriber subscriber = new EventSubscriber();
subscriber.SubscribeToAndRaiseEvent();

Console.Read();
}
}

Nov 16 '05 #8
Thanks Jon,

See my reply to Thomas's post.
--
Mark Allison, SQL Server MVP
http://www.markallison.co.uk

Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602m.html
Jon Skeet [C# MVP] wrote:
Mark Allison <ma***@no.tinned.meat.mvps.org> wrote:
OK, let me put this into my own words, and then you can slap me down. ;-)

You create a delegate called public delegate void MyDelegate(int i) -
this delegate runs code with the same sig. Cool, got that.

You then define your event as follows:
public event MyDelegate MyEvent;

I don't acutally understand the above line of code. What is that
effectively declaring?

It's effectively declaring a field, an event and two operations on the
event. An event has add/remove operations, each of which take a
compatible delegate instance as their parameter. The C# compiler adds
these in by default if you don't specify them. The exact naming and
semantics are unfortunately not defined in the specification, but it's
something like:

public event SomeDelegate Name;

translates to

// This is what stores the actual invocation list.
private SomeDelegate _Name;

// This is the public side of things
public event SomeDelegate Name
{
add
{
lock (this)
{
_Name += value;
}
}
remove
{
lock (this)
{
_Name -= value;
}
}
}

See http://www.pobox.com/~skeet/csharp/t...ckchoice.shtml for a
more thread-safe version.

When you attach the event to the delegate are you "firing the event",
raising the event?

No, you're subscribing to the event.

I want the event to be listened to from another class
altogether from this one. How do I get that other class to listen to
events in this class?

Here's a two-class (plus delegate definition) example:

using System;

delegate void TestDelegate();

class EventHolder
{
public event TestDelegate Foo;

public void RaiseEvent()
{
if (Foo != null)
{
Foo();
}
}
}

class Client
{
static void Main()
{
EventHolder holder = new EventHolder();

holder.Foo += new TestDelegate(First);
holder.Foo += new TestDelegate(Second);

holder.RaiseEvent();
}

static void First()
{
Console.WriteLine("First");
}

static void Second()
{
Console.WriteLine("Second");
}
}
Note that the event delegate ends up as a multicast delegate (I think
single cast delegates are effectively obsolete) so you can effectively
make one delegate out of lots - it just ends up calling them all in
turn.

I was confused for a while as to what the difference between a delegate
and an event was - and basically it's an encapsulation issue. An event
really just encapsulates adding and removing delegates (handlers). A
delegates itself has that and the ability to be fired. Note that from
Client I couldn't have called holder.Foo() directly - I can only add
and remove delegates. Similarly, events can be implemented without a
straight delegate member variable - some classes may have hundreds of
potential events, most of which aren't subscribed to by anything. In
that case, it makes sense to have some other data structure (eg a list
of events which *have* been subscribed to). The event encapsulation
allows that to happen.

Nov 16 '05 #9
On Tue, 21 Sep 2004 12:29:37 +0100, Mark Allison wrote:
Thanks Thomas,

What I don't understand is that the Client Raised the event.
Technically speaking, the client didn't raise the event: the client *asked*
the server to raise the event, and the server raised it.

I wrote the code like this to make it easy to understand.
How would I do that? I don't want the subscribing class to raise the
event, I want it to react to an event, i.e. listen to an event.


Take my example and remove the part where the client asks the server to
raise an event. Arrange matters so that the server raises the event as a
result of something other than the client asking it to. :-)

P.S.: Two corrections to my code:

o EventRaiser.RaiseEvent should check that the event has subscribers
before trying to raise it:

public void RaiseEvent() {
if (DemoEvent != null) {
DemoEvent(123);
}
}

o eventRaiser doesn't need to be a member of EventSubscriber; it could
be a local variable and achieve the same result.
Nov 16 '05 #10
Mark Allison <ma***@no.tinned.meat.mvps.org> wrote:
What I don't understand is that the Client Raised the event. I want the
Client to subscribe to the event and listen to see if anything
interesting happens in EventRaiser.
The client raising the event (or rather, calling a method which happens
to raise the event) is incidental to these examples - it's just a way
of demonstrating things.
Let me describe my scenario. I have a class which I would like to raise
events from, these events need to pass a string. I have another class
which will listen for these events, and then print the string to the
Console using Console.WriteLine.

How would I do that? I don't want the subscribing class to raise the
event, I want it to react to an event, i.e. listen to an event.


Just define a delegate which takes a string, and then have an event of
that type. When you choose to raise the event is up to you.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #11
Jon,

I sent you private mail, I hope you don't mind. :-)


Jon Skeet [C# MVP] wrote:
Mark Allison <ma***@no.tinned.meat.mvps.org> wrote:
What I don't understand is that the Client Raised the event. I want the
Client to subscribe to the event and listen to see if anything
interesting happens in EventRaiser.

The client raising the event (or rather, calling a method which happens
to raise the event) is incidental to these examples - it's just a way
of demonstrating things.

Nov 16 '05 #12
Mark Allison <ma***@no.tinned.meat.mvps.org> wrote:
I sent you private mail, I hope you don't mind. :-)


No problem. For the benefit of others, here's the example I've sent
though, showing the event being raised separately from the client code:

using System;
using System.Threading;

delegate void StringDelegate (string value);

class EntryPoint
{
static void Main()
{
EventGenerator eg = new EventGenerator();
Client c = new Client();
eg.SomeEvent += new StringDelegate(c.CatchEvent);

eg.Start();
}
}

class EventGenerator
{
public event StringDelegate SomeEvent;

public void Start()
{
while (true)
{
if (SomeEvent != null)
{
SomeEvent(DateTime.Now.ToString());
}
Thread.Sleep(1000);
}
}
}

class Client
{
public void CatchEvent (string value)
{
Console.WriteLine (value);
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #13
Hey Jon,

Guess what? The penny dropped! :-) I had one of those moments when the
fog dissipated and I basked in the light of c# delegate and event
handling understanding.

Thanks for your patience! My app works beautifully! :-)

--
Mark Allison, SQL Server MVP
http://www.markallison.co.uk

Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602m.html
Jon Skeet [C# MVP] wrote:
Mark Allison <ma***@no.tinned.meat.mvps.org> wrote:
I sent you private mail, I hope you don't mind. :-)

No problem. For the benefit of others, here's the example I've sent
though, showing the event being raised separately from the client code:

using System;
using System.Threading;

delegate void StringDelegate (string value);

class EntryPoint
{
static void Main()
{
EventGenerator eg = new EventGenerator();
Client c = new Client();
eg.SomeEvent += new StringDelegate(c.CatchEvent);

eg.Start();
}
}

class EventGenerator
{
public event StringDelegate SomeEvent;

public void Start()
{
while (true)
{
if (SomeEvent != null)
{
SomeEvent(DateTime.Now.ToString());
}
Thread.Sleep(1000);
}
}
}

class Client
{
public void CatchEvent (string value)
{
Console.WriteLine (value);
}
}

Nov 16 '05 #14
Mark Allison <ma***@no.tinned.meat.mvps.org> wrote:
Guess what? The penny dropped! :-) I had one of those moments when the
fog dissipated and I basked in the light of c# delegate and event
handling understanding.

Thanks for your patience! My app works beautifully! :-)


Excellent - glad it's all working :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1755
by: Marty McDonald | last post by:
It is still unclear to me why we would use events when delegates seem to do just fine. People say that events make it so the publisher doesn't need to know about the listeners. What does that...
0
375
by: Steven Brown | last post by:
I'm trying to figure out how to safely use .NET events/delegates in a thread-safe class. There are a couple problems. One is that the standard "if(EventName != null) EventName(...);" call can...
3
1571
by: Chris | last post by:
Hi, what is the difference between using events and delegates (apart from the syntax) ? have a look at following (working) programs please (you can just copy/paste and build it) : First...
4
5815
by: Tim | last post by:
There are a set of clients who need to be notified of certain events. I have used events and delegates (publisher-Subscriber model) for the notification mechanism. All the clients register with...
30
3608
by: Burkhard | last post by:
Hi, I am new to C# (with long year experience in C++) and I am a bit confused by the language construct of events. What is it I can do with events that I cannot do with delegates? At the moment...
2
2331
by: kristian.freed | last post by:
Hi, I currently work in a project written fully in C# where we make extensive use of delegates and events. We have a model where a "state", an object holding data but not much code but which...
5
2383
by: raylopez99 | last post by:
I understand delegates (static and non-static) and I agree they are very useful, and that the "Forms" used in the Windows .NET API could not work without them. That said, I'm curious as to how...
7
3406
by: Siegfried Heintze | last post by:
I'm studying the book "Microsoft Visual Basic.NET Language Reference" and I would like some clarify the difference between events and delegates. On page 156 I see a WinForms example of timer that...
9
3093
by: raylopez99 | last post by:
Hello all— I’m trying to get the below to work and cannot get the format right. It’s from this example: http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx What it is: I’m trying...
0
7245
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7356
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7085
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
5069
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3214
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1577
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
785
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
449
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.