473,396 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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.WriteLine("Select highest of {0}, {1}: {2}", a, b,
doSort(high, a, b, c));
Console.WriteLine("Select lowest of {0}, {1}: {2}", a, b,
doSort(low, a, b, c));
Console.WriteLine("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 1987
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.com
"^MisterJingo^" <mi*********@gmail.com> wrote in message
news:11*********************@g49g2000cwa.googlegro ups.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.WriteLine("Select highest of {0}, {1}: {2}", a, b,
doSort(high, a, b, c));
Console.WriteLine("Select lowest of {0}, {1}: {2}", a, b,
doSort(low, a, b, c));
Console.WriteLine("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

"^MisterJingo^" <mi*********@gmail.com> wrote in message
news:11*********************@g49g2000cwa.googlegro ups.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.WriteLine("Select highest of {0}, {1}: {2}", a, b,
doSort(high, a, b, c));
Console.WriteLine("Select lowest of {0}, {1}: {2}", a, b,
doSort(low, a, b, c));
Console.WriteLine("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.WriteLine("Select highest of {0}, {1}: {2}", a, b,
doSort(high, a, b, c));
Console.WriteLine("Select lowest of {0}, {1}: {2}", a, b,
doSort(low, a, b, c));
Console.WriteLine("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 CompleteDelegate(string result);

class Test
{
public event CompleteDelegate Completed;
public void DoSomething()
{
// do something
if (Completed != null) Completed("finished");
}
}

class Other
{
public static void CompletedStatic(string
result){Console.WriteLine(result);}
public void CompletedInstance(string
result){Console.WriteLine(result);}
}

// Use it
Test test = new Test();
Other obj = new Other();
// delegates can be combined...
test.Completed += new CompleteDelegate(Other.CompletedStatic);
test.Completed += new CompleteDelegate(obj.CompletedInstance);
test.DoSomething();
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
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...
1
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...
2
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...
1
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...
3
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...
4
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...
2
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...
6
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,...
8
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...
3
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...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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
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...
0
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...
0
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,...

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.