473,883 Members | 2,484 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Delegates are useful, and here is why (sample program)

They usually don't teach you in most textbooks I've seen that
delegates can be used to call class methods from classes that are
'unaware' of the delegate, so long as the class has the same signature
for the method (i.e., as below, int Square (int)).

Here is an example to show that feature. Note class "UnAwareCla ss"
has its methods Square and Cuber called by a class DelegateClass.
This is because these methods in UnAwareClass have the same signature
and so they can be called by DelegateClass, without the keyword
'delegate' ever appearing in UnAwareClass.

Note the keyword 'static' has to be used as below, even though
UnAwareClass itself is not static, though there is a way to use
delegates with non-static functions (however I don't see the need to
do so).

Pretty cool if you ask me--like a functor in C++.

RL

//Delegate model showing how another class (“UnAwareClass” ) does not
even have to be aware of the delegate and still be called and
employed.
///

///////
// OUTPUT (takes the square of a number, here 11, and the cube, to
give 121 and 1331)

...now for external use of delegates from two classes...
Square 11 is: 121
!Cube 11 is: 1331
Press any key to continue . . .
///////

using System;
using System.Collecti ons.Generic;
using System.Text;

namespace EventDelegates
{
class Program
{
static void Main(string[] args)
{

UnAwareClass myUnAwareClass = new UnAwareClass();

// now to access delegate from another class

Console.WriteLi ne("...now for external use of delegates from two
classes...");

DelegateClass.P ublicHigherPowe r2 sQr = new
DelegateClass.P ublicHigherPowe r2(UnAwareClass .Square); //!!! Note: how
called: UnAwareClass.Sq uare

DelegateClass myDelegateClass = new DelegateClass() ; //
apparently no ill effects if follows rather than preceeds previous
line

int ji2 = myDelegateClass .DoOp(sQr, 11);

Console.WriteLi ne("Square 11 is: {0}", ji2);

DelegateClass.P ublicHigherPowe r2 Cub2 = new
DelegateClass.P ublicHigherPowe r2(UnAwareClass .Cuber);

//!!! note: how called: UnAwareClass.Cu ber

ji2 = myDelegateClass .DoOp(Cub2, 11);

Console.WriteLi ne(" !Cube 11 is: {0}", ji2);

// !!!Note significance: 'delegate' keyword NEVER APPEARS in class
UnAwareClass (!)

}
}
}
////////////
using System;
using System.Collecti ons.Generic;
using System.Text;

namespace EventDelegates
{
class UnAwareClass
{

//!! in this version, 'delegate' keyword does not appear in
this class (UnAwareClass) but only DelegateClass class

int[] values;
int i;
public UnAwareClass()
{
values = new int[] { 1, 2, 3 }; //not used
i = 22333; //not used
}
public static int Square(int x)
{
return x * x;
}
public static int Cuber(int y)
{
return y * y * y;
}
}

class DelegateClass
{
public delegate int PublicHigherPow er2(int x); //delegate to
be used externally (keyword delegate must of course be declared here)

int j;
public DelegateClass()
{
j = 0;
}

public int DoOp(PublicHigh erPower2 ar, int x) //note format
{
return ar(x);
}
}

}
Jul 13 '08
69 5611
On Jul 18, 4:35*pm, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
In particular, your claim that:

<quote>
Eventhandler delegates used in a class can (it's complicated) use a
protected virtual method that fires the event but must have prefix "On"
as the name of the method.
</quote>

is incorrect in the general case.
Perhaps the prefix "On" is, I agree. But it seems to me EventArgs-
style signatures have a particular format. I will experiment with
this in Console mode and if there's anything of interest will post a
sample program for future generations to ponder later today.

RL
Jul 19 '08 #31
On Jul 19, 2:11*pm, raylopez99 <raylope...@yah oo.comwrote:
Hay bozo: *I said: "events are fired when using the System.EventArg s
class, which apparently is manditory,
It is _not_ mandatory.
as is the "On" prefix for any member function that uses an "EventArgs"
type delegate. "
And neither is this.

With regard to "proof", I can only refer you to the C# 3.0 Language
Specification, available directly from Microsoft:

http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx

If you can find anything at all in it regarding EventArgs or "On..."
being mandatory, you're welcome to share it with me. In fact, it would
be interesting if you can find any mention of EventArgs whatsoever
aside from the (non-normative) code samples.
Jul 19 '08 #32
raylopez99 <ra********@yah oo.comwrote:
Hay bozo: I said: "events are fired when using the System.EventArg s
class, which apparently is manditory,
as is the "On" prefix for any member function that uses an "EventArgs"
type delegate. "

Refute that?
Very easily:

using System;

class Test
{
public event Action Foo;
public event EventHandler Bar;

protected void FireBar(EventAr gs args)
{
Bar(this, args);
}

static void Main()
{
Test t = new Test();
t.Foo += () =Console.WriteL ine("First");
t.Bar += (sender, args) =Console.WriteL ine("Second");

t.Foo();
t.FireBar(Event Args.Empty);
}
}

Note that "FireBar" doesn't begin with "On", and "Foo" is an event
which doesn't use EventArgs.
By the way, it might be a good idea to check whether this is also true
(as it seems to be for your posts so far, invariably) for whatever it
is you're going to post next. Perhaps it's not worth the bother, after
all.

Perhaps you can killfile me and avoid having the reply, since you're
obsessive compulsive. Or just take your 20 mg Prozac, like your
doctor says.
Some of us just care about accuracy, that's all. It would also be
preferable to avoid the ad hominem attacks.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jul 19 '08 #33
raylopez99 <ra********@yah oo.comwrote:
Perhaps the prefix "On" is, I agree. But it seems to me EventArgs-
style signatures have a particular format. I will experiment with
this in Console mode and if there's anything of interest will post a
sample program for future generations to ponder later today.
Any delegate instance of the type EventHandler has to have the right
signature, yes - but that's true of all delegate types. The type
defines the required (or at least compatible) signature. EventHandler's
signature is
void EventHandler(ob ject sender, EventArgs e)
but there's nothing magical about it - that's just how it's been
defined.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jul 19 '08 #34
On Jul 19, 6:33*am, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
>
using System;

class Test
{
* * public event Action Foo;
* * public event EventHandler Bar;

* * protected void FireBar(EventAr gs args)
* * {
* * * * Bar(this, args);
* * }

* * static void Main()
* * {
* * * * Test t = new Test();
* * * * t.Foo += () =Console.WriteL ine("First");
* * * * t.Bar += (sender, args) =Console.WriteL ine("Second");

* * * * t.Foo();
* * * * t.FireBar(Event Args.Empty);
* * }

}

Note that "FireBar" doesn't begin with "On", and "Foo" is an event
which doesn't use EventArgs.
Note: this example did not compile (10 errors). Some errors were
easy to fix (I think), like adding <intin public event Action <int>
Foo, but some, like you "lambda expression" is incomprehensibl e to
me. Can you please drop the =expression and give a cleaner
example? I'd like to go through it and learn something.
Some of us just care about accuracy, that's all. It would also be
preferable to avoid the ad hominem attacks.
Yes, I hear you, but I think you're just too sensitive. The other
dude didn't complain, but I'll tone it down some.

RL
Jul 19 '08 #35
On Jul 19, 4:02*am, Pavel Minaev <int...@gmail.c omwrote:
On Jul 19, 2:11*pm, raylopez99 <raylope...@yah oo.comwrote:
Hay bozo: *I said: "events are fired when using the System.EventArg s
class, which apparently is manditory,

It is _not_ mandatory.
Yes, it is (in my mind's eye). We are talking about two different
things. See the post by Jon Skeet--he has what I have in mind. Never
mind his example doesn't compile. The issue is: when you use
EventArgs, is there a particular format? yes there is. The book
C#3.0 Nutshell by Albahari et al states: "With an EventArgs subclass
in place, ...there are three rules: 1/ it must have a void return
type 2/ it must accept two arguments, the first of type object, adn
the second a subclass of EventArgs; the first argument, object,
indicates the event broadcaster, and the second argument contains the
extra information to convey. 3/ Its name must end in "EventHandl er".

Now that's what the book sez. It could be 'convention', or, it could
be manditory. In my mind's eye it's the same thing.

Sorry to flame you BTW, but I found I get more responses on usenet
when I'm rude. I'll tone it down a bit because Jon and Peter are
sensitive souls.

RL
Jul 19 '08 #36
raylopez99 <ra********@yah oo.comwrote:
Note that "FireBar" doesn't begin with "On", and "Foo" is an event
which doesn't use EventArgs.

Note: this example did not compile (10 errors).
It compiles perfectly for me. Perhaps you're not using a C# 3 compiler,
or .NET 3.5?
Some errors were
easy to fix (I think), like adding <intin public event Action <int>
Ah, that strongly suggests you've only got .NET 2.0 or 3.0 installed.
Foo, but some, like you "lambda expression" is incomprehensibl e to
me. Can you please drop the =expression and give a cleaner
example? I'd like to go through it and learn something.
Here's a version which will (I believe) compile with .NET 2.0.

using System;

class Test
{
public event Action<intFoo;
public event EventHandler Bar;

protected void FireBar(EventAr gs args)
{
Bar(this, args);
}

static void Main()
{
Test t = new Test();
t.Foo += delegate { Console.WriteLi ne("First"); };
t.Bar += delegate { Console.WriteLi ne("Second"); };

t.Foo(10);
t.FireBar(Event Args.Empty);
}
}
Some of us just care about accuracy, that's all. It would also be
preferable to avoid the ad hominem attacks.

Yes, I hear you, but I think you're just too sensitive. The other
dude didn't complain, but I'll tone it down some.
I hope so - because you're being *incredibly* rude. You just don't
start calling people "bozo" and recommending they take Prozac - it's
not the way things are done in polite discussions. It's not like this
is the first ad hominem attack you've launched, either. Just because
other people may not respond doesn't make your approach any more
palatable. Bear in mind that you're asking people to help you here -
insulting them isn't going to get you anywhere. Would you act like this
in real life?

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jul 19 '08 #37
raylopez99 <ra********@yah oo.comwrote:
Hay bozo: *I said: "events are fired when using the System.EventArg s
class, which apparently is manditory,
It is _not_ mandatory.
Yes, it is (in my mind's eye). We are talking about two different
things.
In that case you haven't explained yourself clearly enough. Your
statement that "events are fired when using the System.EventArg s class,
which apparently is mandatory" is wrong in itself. Yes, you have to use
EventArgs for an event *of type EventHandler* but that's a very
different statement.
See the post by Jon Skeet--he has what I have in mind. Never
mind his example doesn't compile.
It does, just not under C# 2. Given that you're reading C# 3.0 in a
Nutshell, it would really help you to have a C# 3 compiler installed.
The issue is: when you use
EventArgs, is there a particular format? yes there is. The book
C#3.0 Nutshell by Albahari et al states: "With an EventArgs subclass
in place, ...there are three rules: 1/ it must have a void return
type 2/ it must accept two arguments, the first of type object, adn
the second a subclass of EventArgs; the first argument, object,
indicates the event broadcaster, and the second argument contains the
extra information to convey. 3/ Its name must end in "EventHandl er".
What you didn't explain is that it's under a heading of "Standard Event
Pattern". The pattern is *not* enforced by anything, it's just a
convention. It's worth being very clear about the difference between
patterns/conventions and what is valid code.

It's valid to declare a property with the name @int - but it would be
daft to do so, and violate naming conventions left, right and centre.
Now that's what the book sez. It could be 'convention', or, it could
be manditory. In my mind's eye it's the same thing.
Then your "mind's eye" is incorrect. There's a difference between a
*requirement* and a *recommendation *.
Sorry to flame you BTW, but I found I get more responses on usenet
when I'm rude. I'll tone it down a bit because Jon and Peter are
sensitive souls.
You may get more of a response in terms of *volume* when you're rude,
but you'll find that you actually *learn* a lot more quickly when
you're polite, because people don't need to waste time trying to teach
you manners.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jul 19 '08 #38
On Jul 19, 8:39*am, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
raylopez99 <raylope...@yah oo.comwrote:
Note that "FireBar" doesn't begin with "On", and "Foo" is an event
which doesn't use EventArgs.
Note: *this example did not compile (10 errors).

It compiles perfectly for me. Perhaps you're not using a C# 3 compiler,
or .NET 3.5?
Using 2.0. I rewrote your code to conform with my "old style" and it
works. See below. I don't know what "Action" (a keyword) means, and
your use of 'anonymous' or 'inline' delegates is not for me, though I
understand you can 'capture code' and make it sort of a local variable
that way, though looks too confusing to get into. Note also you have
to input something for EventHandler, namely,
t.FireBar(Event Args.Empty), so you have to input .Empty, which is
something I agree with, and I think you do too. But you made your
point, and I understand it and was apparently mistaking "convention "
with a hard and fast rule about EventHandler. Thanks for clearing
that up.
namespace DelegateSimple0 1
{

class Test
{
public delegate void FooEventHandler (int i);

//public event Action<intFoo;
public event FooEventHandler Fool;
public event EventHandler Bar;
protected void FireBar(EventAr gs args)
{
Bar(this, args);
}
static void Main()
{
Test t = new Test();
//t.Foo += delegate { Console.WriteLi ne("First"); };

t.Fool += new FooEventHandler (Foo);
t.Bar += delegate { Console.WriteLi ne("Second"); };

t.Fool(10);
t.FireBar(Event Args.Empty);
}
static void Foo(int ii)
{
Console.WriteLi ne("First,hello !");
}
}

}

>
Yes, I hear you, but I think you're just too sensitive. *The other
dude didn't complain, but I'll tone it down some.

I hope so - because you're being *incredibly* rude. You just don't
start calling people "bozo" and recommending they take Prozac - it's
not the way things are done in polite discussions.
Yes, but this is Usenet.

It's not like this
is the first ad hominem attack you've launched, either. Just because
other people may not respond doesn't make your approach any more
palatable. Bear in mind that you're asking people to help you here -
insulting them isn't going to get you anywhere. Would you act like this
in real life?
Yes, sometimes. And it doesn't hurt. In fact, a study once found that
people who are "jerks" end up with little or no negative things
happening to their career. Early in my career, straight out of
school, one of my bosses, who had real clout, once told me: "after you
leave here [he fired me] you'll never work in this field again, I'll
make sure of it" (because of his prestigious position, even if you
wanted to you could not easily sue him for defamation, not that I
would sue him, since I don't believe in lawsuits). He tried his best,
giving me negative recommendations , and despite him I got a better job
and never looked back. But, that does not mean you should be a jerk--
being nice, as I learned in California, gets the job done easier
(Persian expression about honey attracting flies--then again, shitte
attracts flies too)--but at the end of the day, the nice guys, bad
guys, jerks (good, bad and ugly) end up roughly in the same place,
inline with fortune, fate, and their own innate abilities. However,
having said that, since I appreciate your input and feel you might
stop replying to me, I will tone it down some. Like you say you're
not being paid to answer me.

Thanks for your help. I appreciate it and you've done a lot of good
over the years replying to people (I see some of your posts in the
archives when I Google an answer to a problem).

RL
Jul 19 '08 #39
On Jul 19, 9:02*pm, raylopez99 <raylope...@yah oo.comwrote:
Using 2.0. *I rewrote your code to conform with my "old style" and it
works. *See below. *I don't know what "Action" (a keyword) means
It's not a keyword. It's System.Action<T delegate type declared like
this:

delegate void Action<T>(T arg);

So, basically, a general type for single-argument procedures.

Jon's original code used System.Action (without T), which was
introduced in .NET 3.5, and is essentially a no-argument version of
the above:

delegate void Action();
Jul 19 '08 #40

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

Similar topics

4
3241
by: Phil G. | last post by:
I was recently struggling to adapt an example I have using delegate methods, IasynResult and AsynCallback. Doing a little research I came across an example, which in fact was being used to return data from an external sql database...exactly what I am doing. This example used the System.Threading namespace and thread.start etc What are the pro's and con's of using/choosing either option? They both 'appear' to create a process on a new...
12
206
by: tshad | last post by:
I have a set up javascript functions that pass function pointers and I am trying to figure out how to do the same thing in C# using delegates. // We define some simple functions here function add(x,y) {return x + y;} function subtract(x,y) {return x - 1; } function multiply(x,y) {return x * 1; }
0
9944
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11154
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10863
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7977
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7136
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5807
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6005
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4622
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 we have to send another system
2
4228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.