473,804 Members | 3,425 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Delegate question

Hi all,

I've been trying to get my head around delegates. The book i'm using
had a single example, not much explaination, and didn't show how to set
up a delegate and pass variables in and out of the functions it refers
to. So I've been playing around and came up with he following code. I
know it doesn't do much, but I just wanted to fit together delegates
and parameter passing:

//////////////// Code start

public delegate int Sort(int a, int b, int c);

public class SortProgram
{
public static int doSort(Sort ar, int a, int b, int c)
{
return(ar(a, b,c));
}

public static int highest(int first, int second, int third)
{
int tmp = 0;

if (first > second)
tmp = first;
else
tmp = second;

if (tmp > third)
return tmp;
else
return third;
}

public static int lowest(int first, int second, int third)
{
int tmp = 0;

if (first < second)
tmp = first;
else
tmp = second;

if (tmp < third)
return tmp;
else
return third;
}

public static int middle(int first, int second, int third)
{
int tmp = 0;

if (first > second)
tmp = first;
else
tmp = second;

if (tmp > third)
return third;
else
return second;
}
public static void Main()
{
int a = 90;
int b = 110;
int c = 300;
Sort high = new Sort(highest);
Sort low = new Sort(lowest);
Sort mid = new Sort(middle);

Console.WriteLi ne("Select highest of {0}, {1}: {2}", a, b,
doSort(high, a, b, c));
Console.WriteLi ne("Select lowest of {0}, {1}: {2}", a, b,
doSort(low, a, b, c));
Console.WriteLi ne("Select middle of {0}, {1}: {2}", a, b,
doSort(middle, a, b, c));
}
}

//////////////// Code end

Regarding the code, is this how one would go about using delegetes for
such a function? Or am I doing something wrong / being long winded with
my code?
Is it ok to declare a delegete in the namespace (I figured other
classes could use it if they needed to), or is it best to keep such
declarations to class body?
I gave up on events until I get my head around this, they're on my
list next :).

Any tips, or pointers would be welcomed.

Chris

Dec 14 '05 #1
4 2022
MisterJingo,

What you are doing is pretty much right. The only thing that I would
think is excessive is the call to doSort. You don't need to wrap the
delegate in a method call, you can just call the delegate directly.

Other than that, it looks fine.

The nature of the delegate will determine where I declare it. If I have
a delegate which is specific to the class that will use it, then I will
declare it in the class. However, for general event handlers (like
EventHandler, for instance), I will declare that in a namespace.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"^MisterJin go^" <mi*********@gm ail.com> wrote in message
news:11******** *************@g 49g2000cwa.goog legroups.com...
Hi all,

I've been trying to get my head around delegates. The book i'm using
had a single example, not much explaination, and didn't show how to set
up a delegate and pass variables in and out of the functions it refers
to. So I've been playing around and came up with he following code. I
know it doesn't do much, but I just wanted to fit together delegates
and parameter passing:

//////////////// Code start

public delegate int Sort(int a, int b, int c);

public class SortProgram
{
public static int doSort(Sort ar, int a, int b, int c)
{
return(ar(a, b,c));
}

public static int highest(int first, int second, int third)
{
int tmp = 0;

if (first > second)
tmp = first;
else
tmp = second;

if (tmp > third)
return tmp;
else
return third;
}

public static int lowest(int first, int second, int third)
{
int tmp = 0;

if (first < second)
tmp = first;
else
tmp = second;

if (tmp < third)
return tmp;
else
return third;
}

public static int middle(int first, int second, int third)
{
int tmp = 0;

if (first > second)
tmp = first;
else
tmp = second;

if (tmp > third)
return third;
else
return second;
}
public static void Main()
{
int a = 90;
int b = 110;
int c = 300;
Sort high = new Sort(highest);
Sort low = new Sort(lowest);
Sort mid = new Sort(middle);

Console.WriteLi ne("Select highest of {0}, {1}: {2}", a, b,
doSort(high, a, b, c));
Console.WriteLi ne("Select lowest of {0}, {1}: {2}", a, b,
doSort(low, a, b, c));
Console.WriteLi ne("Select middle of {0}, {1}: {2}", a, b,
doSort(middle, a, b, c));
}
}

//////////////// Code end

Regarding the code, is this how one would go about using delegetes for
such a function? Or am I doing something wrong / being long winded with
my code?
Is it ok to declare a delegete in the namespace (I figured other
classes could use it if they needed to), or is it best to keep such
declarations to class body?
I gave up on events until I get my head around this, they're on my
list next :).

Any tips, or pointers would be welcomed.

Chris

Dec 14 '05 #2
Hi,
Well the code use delegates correctly, you have a procedure from which you
know the signature but that can be different implementations , you wait until
runtime to select the correct alternative.
Take a look at the Strategy pattern:
http://en.wikipedia.org/wiki/Strategy_pattern
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"^MisterJin go^" <mi*********@gm ail.com> wrote in message
news:11******** *************@g 49g2000cwa.goog legroups.com...
Hi all,

I've been trying to get my head around delegates. The book i'm using
had a single example, not much explaination, and didn't show how to set
up a delegate and pass variables in and out of the functions it refers
to. So I've been playing around and came up with he following code. I
know it doesn't do much, but I just wanted to fit together delegates
and parameter passing:

//////////////// Code start

public delegate int Sort(int a, int b, int c);

public class SortProgram
{
public static int doSort(Sort ar, int a, int b, int c)
{
return(ar(a, b,c));
}

public static int highest(int first, int second, int third)
{
int tmp = 0;

if (first > second)
tmp = first;
else
tmp = second;

if (tmp > third)
return tmp;
else
return third;
}

public static int lowest(int first, int second, int third)
{
int tmp = 0;

if (first < second)
tmp = first;
else
tmp = second;

if (tmp < third)
return tmp;
else
return third;
}

public static int middle(int first, int second, int third)
{
int tmp = 0;

if (first > second)
tmp = first;
else
tmp = second;

if (tmp > third)
return third;
else
return second;
}
public static void Main()
{
int a = 90;
int b = 110;
int c = 300;
Sort high = new Sort(highest);
Sort low = new Sort(lowest);
Sort mid = new Sort(middle);

Console.WriteLi ne("Select highest of {0}, {1}: {2}", a, b,
doSort(high, a, b, c));
Console.WriteLi ne("Select lowest of {0}, {1}: {2}", a, b,
doSort(low, a, b, c));
Console.WriteLi ne("Select middle of {0}, {1}: {2}", a, b,
doSort(middle, a, b, c));
}
}

//////////////// Code end

Regarding the code, is this how one would go about using delegetes for
such a function? Or am I doing something wrong / being long winded with
my code?
Is it ok to declare a delegete in the namespace (I figured other
classes could use it if they needed to), or is it best to keep such
declarations to class body?
I gave up on events until I get my head around this, they're on my
list next :).

Any tips, or pointers would be welcomed.

Chris

Dec 14 '05 #3
^MisterJingo^ wrote:
I've been trying to get my head around delegates. The book i'm using
had a single example, not much explaination, and didn't show how to
A delegate is a 'managed function pointer'. It can only be used to call
managed methods (managed methods have a calling convention of clrcall).
Unlike C function pointers, which allow you to cast a function pointer
to any function, a delegate can only be used to call a method with the
exact method prototype of the delegate.
set up a delegate and pass variables in and out of the functions it
refers to. So I've been playing around and came up with he following
If you use C#, the compiler will allow you to call the delegate as if it
is a method, so you just pass the method parameters to the delegate. If
the delegate is to an instance method then the instance is passed to the
constructor of the delegate when you create it.
public delegate int Sort(int a, int b, int c);

public class SortProgram
{
public static int doSort(Sort ar, int a, int b, int c)
{
return(ar(a, b,c));
yes, this is right.
public static int highest(int first, int second, int third);
public static int lowest(int first, int second, int third);
public static int middle(int first, int second, int third); Sort high = new Sort(highest);
Sort low = new Sort(lowest);
Sort mid = new Sort(middle);

Console.WriteLi ne("Select highest of {0}, {1}: {2}", a, b,
doSort(high, a, b, c));
Console.WriteLi ne("Select lowest of {0}, {1}: {2}", a, b,
doSort(low, a, b, c));
Console.WriteLi ne("Select middle of {0}, {1}: {2}", a, b,
doSort(middle, a, b, c));
This is fine.
Regarding the code, is this how one would go about using delegetes for
such a function? Or am I doing something wrong / being long winded
with my code?
It depends what you want to do, but what you have given is OK. Usually
delegates are used to implement events. In general (but not in every
case) the framework library classes use an interface reference when a
method needs to have a parameter that is a pointer to a method, rather
than using a delegate.

An event is formalised metadata that describes the methods to add and
remove delegates from an object. When the compiler sees the event
keyword it generates a delegate field and methods to add and remove
delegates to that field. The C# compiler will call these methods when
you use the += and -= operators on the event member:

delegate void CompleteDelegat e(string result);

class Test
{
public event CompleteDelegat e Completed;
public void DoSomething()
{
// do something
if (Completed != null) Completed("fini shed");
}
}

class Other
{
public static void CompletedStatic (string
result){Console .WriteLine(resu lt);}
public void CompletedInstan ce(string
result){Console .WriteLine(resu lt);}
}

// Use it
Test test = new Test();
Other obj = new Other();
// delegates can be combined...
test.Completed += new CompleteDelegat e(Other.Complet edStatic);
test.Completed += new CompleteDelegat e(obj.Completed Instance);
test.DoSomethin g();
Is it ok to declare a delegete in the namespace (I figured other
classes could use it if they needed to), or is it best to keep such
declarations to class body?
Again, its personal preference, I prefer them to be declared out side of
the class. When the compiler sees a delegate it will create a delegate
class.
I gave up on events until I get my head around this, they're on my
list next :).
Easy, see above <g>.
Any tips, or pointers would be welcomed.


The delegates above are called synchronously, that is, on the thread
that invoked the delegate. You can also call delegates asynchronously,
in which case the runtime will use a thread pool thread (you do not have
to create this thread). You have to worry about the thread safety of
your code/variables in the async case, you don't have to worry in the
sync case.

Richard
--
Fusion Tutorial: http://www.grimes.demon.co.uk/workshops/fusionWS.htm
Security Tutorial:
http://www.grimes.demon.co.uk/workshops/securityWS.htm
Dec 14 '05 #4
Thanks for the replies all, they've helped a lot :).

Chris

Dec 14 '05 #5

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

Similar topics

2
1430
by: Nima | last post by:
The documentation for the Delegate and the MultiCastDelegate classes tell me that when we have a line like: public delegate void CheckAndPrintDelegate(string str); it causes the compiler to generate a new delegate class named CheckAndPrintDelegate that inherits from System.MulticastDelegate. Elsewhere it says the same delegate definition produces a delegate class inheriting from System.Delegate.
1
2752
by: CJ Taylor | last post by:
Alright, I probably wont be able to get this question answered, but maybe someone has even more experience than me with delegates... Wow... that sounded fecisious. =) So, I'm trying to dynamically create a delegate where the parameters match on the base level (position is the same, and there base types are the same.) i.e.
2
3409
by: sg71.cherub | last post by:
Here I am meeting a problem. I am transfering unmanaged C/C++ codes to managed C# codes. For the general C/C++ function pointer, it is easy to implement its function by C# delegate. e.g. Declare (C/C++): double (* f) (double * x, void * parms); Declare (C#): public delegate double f (double x, object parms); And the ways to use them are logically similiar.
1
1826
by: Quimbly | last post by:
I'm having some problems comparing delegates. In all sample projects I create, I can't get the problem to occur, but there is definitely a problem with my production code. I can't give all the code, as there's simply too much, but here's the general gist: I have a connection object which connects to a custom back-end server of one type or another. Clients of this connection object send requests via a method (e.g....
3
3281
by: Peter Duniho | last post by:
I was reminded in a recent post (http://groups.google.com/group/microsoft.public.dotnet.framework/msg/e649e992db857691?dmode=source) that in C# one can use anonymous delegates without explicitly creating a new delegate instance. However, I still run into situations in which the compiler complains. For example, I get a compiler error here: Invoke(delegate() { /* some code */ });
4
1790
by: Bob Cramer | last post by:
I don't have a copy of Reflector handy :-( so I'd appreciate if someone could confirm (or clarify) the following. In consideration of the following delegate declaration... delegate string MyLovelyDelegate(int parm1, string parm2); 1. Is it true that, in the output assembly, a new class will be created that inherits from System.MulticastDelegate - and the name of that class is
2
427
by: Tony Johansson | last post by:
Hello!! Below is a program copied from a book. The program is easy but there is one thing about the program that I would like to have some more info about. Assume that you have for example 10 cars in the array gameCars. Assume also that you want to subscribe to an event for some cars located in the array gameCars.
6
1405
by: damiensawyer | last post by:
Hi, Can someone please explain to me something about delegates? My understanding is as follows. A delegate is basically an object that can hold a reference to a "method" somewhere. That is, it's essentially a pointer to a piece of code somewhere else in memory. It therefore (to me anyway) makes sense to define delegates with their signatures and be able to use those signatures at different points in
8
4376
by: Advait Mohan Raut | last post by:
Hello, I am using VC# 2005 ; C# 2.0 I am working on the performance measurement tool. For that I need my code to call user defined method along with its parameters. For that should I use a generic delegate with variable length argument or something else ? if it is then how to use it ? AA advait
3
1518
by: puzzlecracker | last post by:
Sort of new to internal of delegates. My question is when you create a delegate instance, does the surrounding block must be able to see/access method you want delegate to take on. Here is concrete example: namespace Test public delegate string MyDelegate (int x); class A {
0
9704
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
9571
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10302
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
10069
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...
1
7608
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
6845
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
5505
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
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3803
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.