473,765 Members | 2,053 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 5589
On Wed, 16 Jul 2008 01:41:32 -0700, raylopez99 <ra********@yah oo.com>
wrote:
On Jul 16, 1:31Â*am, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
>No, he hasn't said so explicitly. Â*That's why I asked for a
clarificatio n.

Well, you admit you're confused.
No, I'm not. It's simply that the information is incomplete at this
point. There is, in fact, a difference.
Understood.
Obviously not.
[...]
Speaking of poor programmer, I see Ben Voight has the prestigious [C++
MVP] abbreviation next to his name--funny, I don't see that next to
your name.

That's true, you don't. Â*While I am in fact a recipient of the C# MVP Â*
award, I choose not to include that in my posting credentials. Â*So what?

So you're perhaps not a C# MVP.
If that were true, I would not have written "I am in fact a recipient of
the C# MVP award".
>By the way, if you're going to try to ride on Ben's coat-tails, you
ought Â*
to at least make the effort to spell his name correctly.

Ben Voight. That's his name.
No it's not. But, please...dig your hole as deep as you like.
[...]
>I'm sure Ben will correct me if I'm wrong about that, and if so I'll Â*
welcome the correction. Â*My concern is that the facts are correct, not Â*
whose stream of urine can reach the farthest.

Looks like a flame thread or pissing contest to me, but I could be
wrong.
No "could be" about it. You simply are.

Pete
Jul 16 '08 #21
On Jul 16, 12:31*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
The delegate includes as part of itself the object that will be used in *
invoking the method referenced by the delegate. *In C++, if I recall *
correctly (it's been at least five or six years since I did any serious *
C++ programming), while you can in fact get a function pointer to an *
instance method of a class, you still need to explicitly provide an *
instance when calling the method. *It can't be bound at the time the *
function pointer is created, the way it is with a delegate in C#.
While this is definitely in the offtopic territory now, I'll still
clarify this, for what's it worth...

In C++, pointers to members are not closed over the receiver (i.e.
"this") - this includes both pointers to fields, and pointers to
methods. However, it is obviously trivial to take such an open
pointer, and close it over anything you wish, and there are plenty of C
++ libraries encapsulating this (boost::signal, libsig++, etc);
furthermore, ISO C++ TR1 includes a standard way to do this via
std::tr1::bind. In that way, raw pointers to members are not "object-
oriented" (though what it has to do with OOP as such escapes me), but
they provide a foundational mechanism to implement C#-style delegates.

On the other hand, it not possible to fully imitate the semantics of C+
+ pointers to members in C# using delegates; for example, when it
comes to virtual calls (in C++, calling a virtual function through a
member pointer to it involves full dynamic dispatch at the point of
the call; in C#, resolution happens when you instantiate the
delegate).

Then again, those MSDN claims that delegates are somehow "more object-
oriented" than C++ pointers to members reminds me of how, some time
ago, Java adepts complaned that delegates are "not object-oriented"
compared to Java-style listener interfaces.
Jul 17 '08 #22
>>As far as I know, a C++ function pointer cannot encapsulate the
>>target of
the reference, can it? Would you mind elaborating on what you mean
by "C++ function pointers are object-oriented"?
Simply that there's a variant of function pointers, the pointer-to-member
function pointer, which is designed solely for use with objects.
>>
Would you mind elaborating with "encapsulat e the target of the
reference"--what do you mean by "encapsulat e"?

The delegate includes as part of itself the object that will be used
in invoking the method referenced by the delegate. In C++, if I
recall correctly (it's been at least five or six years since I did
any serious C++ programming), while you can in fact get a function
pointer to an instance method of a class, you still need to
explicitly provide an instance when calling the method. It can't be
bound at the time the function pointer is created, the way it is with
a delegate in C#.
I'm sure Ben will correct me if I'm wrong about that, and if so I'll
welcome the correction. My concern is that the facts are correct, not
whose stream of urine can reach the farthest.
C++ can do that, but you'd be using a functor at that point, not a raw
function pointer. I think boost::bind is the most widely used method to
accomplish that, and unlike .NET delegates, boost::bind can close the call
on any combination of arguments, not just the first.
Jul 17 '08 #23
>>By the way, if you're going to try to ride on Ben's coat-tails, you
>>ought
to at least make the effort to spell his name correctly.

Ben Voight. That's his name.

No it's not. But, please...dig your hole as deep as you like.
Just to set the record straight, Peter is right, Ray keeps slipping in an
extra 'h', and there seems to be no confusion whatsoever who is being
referenced.
Jul 17 '08 #24
On Thu, 17 Jul 2008 00:58:05 -0700, Pavel Minaev <in****@gmail.c omwrote:
[...]
On the other hand, it not possible to fully imitate the semantics of C+
+ pointers to members in C# using delegates; for example, when it
comes to virtual calls (in C++, calling a virtual function through a
member pointer to it involves full dynamic dispatch at the point of
the call; in C#, resolution happens when you instantiate the
delegate).
I think the C# designers consider that a feature. :)
Then again, those MSDN claims that delegates are somehow "more object-
oriented" than C++ pointers to members reminds me of how, some time
ago, Java adepts complaned that delegates are "not object-oriented"
compared to Java-style listener interfaces.
I agree that saying something is or is not "OOP" is difficult to justify,
given how it depends entirely on what standard of "OOP" one is referring
to.

My main point is that I honestly don't see the article as being rife with
"fear, uncertainty, and doubt" at all, never mind to the degree that would
invalidate it as a useful learning tool.

Pete
Jul 17 '08 #25
On Jul 18, 5:55*pm, raylopez99 <raylope...@yah oo.comwrote:
Regarding delegates used as events in the .NET framework--I've
discovered (for me) a shocking non-standard way that 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"
While databinding may take more notice of On* methods, the language
itself couldn't care less. They're just normal methods. Likewise the
language doesn't know anything about EventArgs or EventHandler.

Now, as for the syntax used for creating delegate instances, this is
just a new feature as of C# 2 - implicit conversion of method groups
to delegate instances.

See http://www.csharpindepth.com/Article...ersGuide2.aspx

Jon
Jul 18 '08 #26
On Jul 18, 10:02*am, "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
While databinding may take more notice of On* methods, the language
itself couldn't care less. They're just normal methods. Likewise the
language doesn't know anything about EventArgs or EventHandler.
Fair enough, but this is a .NET group so I imply that it's the NET API
that knows this stuff, through databinding (whatever that is, but I
think it's the stuff Alan Cooper invented with Visual drag and drop
code generated by the wizard).
>
Now, as for the syntax used for creating delegate instances, this is
just a new feature as of C# 2 - implicit conversion of method groups
to delegate instances.

Seehttp://www.csharpindep th.com/Articles/General/BluffersGuide2. aspx
That was good, thanks. I wish I had a bluffer's guide to C# (I've
bought some of their guides in the past for other stuff)

RL

Delegates in C# 2 have a number of improvements over C# 1. The most
important two features are implicit method group conversions and
anonymous methods, both of which make it easier to create new
instances of delegate types. For example:

public void Foo()
{
// Do some stuff
}

// C# 1 code:
ThreadStart ts1 = new ThreadStart(Foo );

// C# 2 code, implicit method group conversion:
ThreadStart ts2 = Foo;

// C# 2, anonymous method:
ThreadStart ts3 = delegate { Console.WriteLi ne("Hi!"); };

There's a lot more to anonymous methods than meets the eye, by the
way...
Jul 18 '08 #27
On Jul 18, 8:55*pm, raylopez99 <raylope...@yah oo.comwrote:
Shocking stuff dontyathink?
Not at all. Aside from a number of things that you've simply got wrong
(such as "On..." methods and EventArgs-style signatures for events
being required), it's all very basic C#, discussed in detail in pretty
much every entry-level book.

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.
Jul 18 '08 #28
raylopez99 <ra********@yah oo.comwrote:
While databinding may take more notice of On* methods, the language
itself couldn't care less. They're just normal methods. Likewise the
language doesn't know anything about EventArgs or EventHandler.

Fair enough, but this is a .NET group so I imply that it's the NET API
that knows this stuff, through databinding (whatever that is, but I
think it's the stuff Alan Cooper invented with Visual drag and drop
code generated by the wizard).
But my point is that it's only very specific bits of .NET which care
about how you name event raising methods. For the most part, you can
call them what you like with no ill effects other than breaking
convention.

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.

--
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 18 '08 #29
On Jul 18, 4:33*pm, Pavel Minaev <int...@gmail.c omwrote:
On Jul 18, 8:55*pm, raylopez99 <raylope...@yah oo.comwrote:
Shocking stuff dontyathink?

Not at all. Aside from a number of things that you've simply got wrong
(such as "On..." methods and EventArgs-style signatures for events
being required), it's all very basic C#, discussed in detail in pretty
much every entry-level book.
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?
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.

RL
Jul 19 '08 #30

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

Similar topics

4
3238
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
9568
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
10156
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...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9951
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,...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6649
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();...
1
3924
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
3531
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.