What s a Delegate?


That s hard to answer, but I ll try. A delegate in Microsoft .NET is a data type, like a class or string or number. It is the .NET managed equivalent of a C function pointer, or a C++ method pointer, or a procedure of object type in Delphi. Let s look at it from that angle for a moment. In C or C++, if f is a pointer to a function, you can say (*f)( hello , 2); and call that function, passing it the arguments "hello" and 2. Very powerful. In ANSI C and C++, these function pointers are checked by the compiler for correctness. In earlier compilers, they were not and you could type most anything in and have it blow up in really interesting ways.

In .NET, a delegate holds on to a specific method, in a specific object instance. Recall that every method can explicitly or implicitly use this to refer to the instance, so a method can t just hang around without being hooked to a specific instance. A delegate might be declared like this:

 public delegate int Combine(int first, int second); 

That just means that there s a kind of delegate (think class) named Combine that holds on to methods that take two integer parameters and return an integer result. An instance of Combine could hold on to any such method. We might have something like this (untested):

 class Pair { 
private int left;
private int right;

private int Total(int a, int b) {
return a + b;
}

private int Prod(int a, int b) {
return a*b;
}

private delegate int Combine(int first, int second);

private Combine action;

public void MultiplyFromNowOn() {
action = this.Prod;
}

public void AddFromNowOn() {
action = this.Total;
}

public int WhatsTheAnswer() {
return action(left, right);
}
}

With an instance of this class in hand, if we send it MultiplyFromNowOn, then whenever we ask it WhatsTheAnswer, it will reply with the product of left and right. But if we send it AddFromNowOn, it will return the sum until further notice.

Probably you can see that this is quite analogous to the code in the previous chapter, where we would have used the string MultiplyFromNowOn instead of the actual method name. An important difference is that if there happens to be a typo in the string ”and as it turns out there is ”my approach will discover the error only at run time. If we use delegates, the name of the method is checked at compile time. With my approach, if we used the right name but the wrong kind of function, that too would be discovered only at run time. Delegates check the method prototype, not just its name.

Kevin was right: delegates are a lot better.




Extreme Programming Adventures in C#
Javaв„ў EE 5 Tutorial, The (3rd Edition)
ISBN: 735619492
EAN: 2147483647
Year: 2006
Pages: 291

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net