Delegate question

M

^MisterJingo^

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
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
I

Ignacio Machin \( .NET/ C# MVP \)

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,
 
R

Richard Grimes

^MisterJingo^ said:
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 said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top