Delegates


Delegates exist for situations in which you want to pass methods around to other methods. To see what that means, consider this line of code:

 int i = int.Parse("99"); 

You are so used to passing data to methods as parameters, as in this example, you don't consciously think about it; and for this reason the idea of passing methods around instead of data might sound a little strange. However, there are cases in which you have a method that does something, and rather than operating on data, the method might need to do something that involves invoking another method. To complicate things further, you do not know at compile-time what this second method is. That information is available only at runtime and hence will need to be passed in as a parameter to the first method. That might sound confusing but should be clearer with a couple of examples:

  • Starting Threads — It is possible in C# to tell the computer to start some new sequence of execution in parallel with what it is currently doing. Such a sequence is known as a thread, and starting one up is done using the Start() method on an instance of one of the base classes, System.Threading.Thread. If you tell the computer to start a new sequence of execution, you have to tell it where to start that sequence. You have to supply it with the details of a method in which execution can start. In other words, the Thread.Start() method has to take a parameter that defines the method to be invoked by the thread.

  • Generic Library Classes — Many libraries contain code to perform various standard tasks. It is usually possible for these libraries to be self-contained, in the sense that you know when you write to the library exactly how the task must be performed. However, sometimes the task contains some subtask, which only the individual client code that uses the library knows how to perform. For example, say you want to write a class that takes an array of objects and sorts them into ascending order. Part of the sorting process involves repeatedly taking two of the objects in the array and comparing them in order to see which one should come first. If you want to make the class capable of sorting arrays of any object, there is no way that it can tell in advance how to do this comparison. The client code that hands your class the array of objects will also have to tell your class how to do this comparison for the particular objects it wants sorted. The client code will have to pass your class details of an appropriate method that can be called and does the comparison.

  • Events — The general idea here is that often you have code that needs to be informed when some event takes place. GUI programming is full of situations like this. When the event is raised, the runtime will need to know what method should be executed. This is done by passing the method that handles the event as a parameter to a delegate. This is discussed later in the chapter.

So, now that you understand the principle that, sometimes, methods need to take details of other methods as parameters, you need to figure out how you can do that. The simplest way would appear to be to just pass in the name of a method as a parameter. To take the example from threading, suppose you are going to start a new thread, and you have a method called EntryPoint(), which is where you want your thread to start running:

 void EntryPoint() { // do whatever the new thread needs to do } 

Alternatively, you can start the new thread off with some code like this:

 Thread NewThread = new Thread(); Thread.Start(EntryPoint);                   // WRONG 

In fact, this is the simple way of doing it, and it is what some languages, such as C and C++, do in this kind of situation (in C and C++, the parameter EntryPoint is the function pointer).

Unfortunately, this direct approach causes some problems with type safety, and it also neglects the fact that when you are doing object-oriented programming, methods rarely exist in isolation, but usually need to be associated with a class instance before they can be called. As a result of these problems, the.NET Framework does not syntactically permit this direct approach. Instead, if you want to pass methods around, you have to wrap up the details of the method in a new kind of object, a delegate. Delegates quite simply are a special type of object — special in the sense that, whereas all the objects defined up to now contain data, a delegate just contains the details of a method.

Declaring Delegates in C#

When you want to use a class in C#, you do so in two stages. First, you need to define the class — that is, you need to tell the compiler what fields and methods make up the class. Then (unless you are using only static methods), you instantiate an object of that class. With delegates it is the same thing. You have to start off by defining the delegates you want to use. In the case of delegates, defining them means telling the compiler what kind of method a delegate of that type will represent. Then, you have to create one or more instances of that delegate.

The syntax for defining delegates looks like this:

 delegate void VoidOperation(uint x);  

In this case, you have defined a delegate called VoidOperation, and you have indicated that each instance of this delegate can hold a reference to a method that takes one uint parameter and returns void. The crucial point to understand about delegates is that they are very type-safe. When you define the delegate, you have to give full details of the signature of the method that it is going to represent.

Important

One good way of understanding delegates is by thinking of a delegate as something that gives a name to a method signature.

Suppose you wanted to define a delegate called TwoLongsOp that will represent a function that takes two longs as its parameters and returns a double. You could do it like this:

 delegate double TwoLongsOp(long first, long second); 

Or, to define a delegate that will represent a method that takes no parameters and returns a string, you might write this:

 delegate string GetAString(); 

The syntax is similar to that for a method definition, except that there is no method body and the definition is prefixed with the keyword delegate. Because what you are doing here is basically defining a new class, you can define a delegate in any of the same places that you would define a class — that is to say either inside another class or outside of any class and in a namespace as a top-level object. Depending on how visible you want your definition to be, you can apply any of the normal access modifiers to delegate definitions — public, private, protected, and so on:

 public delegate string GetAString(); 
Note

We really mean what we say when we describe defining a delegate as defining a new class. Delegates are implemented as classes derived from the class System.MulticastDelegate, which is derived from the base class, System.Delegate. The C# compiler is aware of this class and uses its delegate syntax to shield you from the details of the operation of this class. This is another good example of how C# works in conjunction with the base classes to make programming as easy as possible.

After you have defined a delegate, you can create an instance of it so that you can use it to store details of a particular method.

Note

There is an unfortunate problem with terminology here. With classes there are two distinct terms — class, which indicates the broader definition, and object, which means an instance of the class. Unfortunately, with delegates there is only the one term. When you create an instance of a delegate, what you have created is also referred to as a delegate. You need to be aware of the context to know which meaning we are using when we talk about delegates.

Using Delegates in C#

The following code snippet demonstrates the use of a delegate. It is a rather long-winded way of calling the ToString() method on an int:

 private delegate string GetAString(); static void Main(string[] args) { int x = 40; GetAString firstStringMethod = new GetAString(x.ToString); Console.WriteLine("String is" + firstStringMethod()); // With firstStringMethod initialized to x.ToString(),  // the above statement is equivalent to saying  // Console.WriteLine("String is" + x.ToString()); 

In this code, you instantiate a delegate of type GetAString, and you initialize it so that it refers to the ToString() method of the integer variable x. Delegates in C# always syntactically take a one-parameter constructor, the parameter being the method to which the delegate will refer. This method must match the signature with which you originally defined the delegate. So in this case, you would get a compilation error if you tried to initialize firstStringMethod with any method that did not take parameters and return a string. Notice that because int.ToString() is an instance method (as opposed to a static one) you need to specify the instance (x) as well as the name of the method to initialize the delegate properly.

The next line actually uses the delegate to display the string. In any code, supplying the name of a delegate instance, followed by brackets containing any parameters, has exactly the same effect as calling the method wrapped by the delegate. Hence, in the preceding code snippet, the Console.WriteLine() statement is completely equivalent to the commented-out line.

One feature of delegates is that they are type-safe to the extent that they ensure the signature of the method being called is correct. However, interestingly, they do not care what type of object the method is being called against or even whether the method is a static method or an instance method.

Important

An instance of a given delegate can refer to any instance or static method on any object of any type, provided that the signature of the method matches the signature of the delegate.

To demonstrate this, the following example expands the previous code snippet so that it uses the firstStringMethod delegate to call a couple of other methods on another object — an instance method and a static method. For this, you use the Currency struct, which is defined as follows:

 struct Currency { public uint Dollars; public ushort Cents; public Currency(uint dollars, ushort cents) { this.Dollars = dollars; this.Cents = cents; } public override string ToString() { return string.Format("${0}.{1,-2:00}", Dollars,Cents); } public static explicit operator Currency (float value) { checked { uint dollars = (uint)value; ushort cents = (ushort)((value-dollars)*100); return new Currency(dollars, cents); } } public static implicit operator float (Currency value) { return value.Dollars + (value.Cents/100.0f); } public static implicit operator Currency (uint value) { return new Currency(value, 0); } public static implicit operator uint (Currency value) { return value.Dollars; } } 

Notice that the Currency struct has its own overload of ToString(). To demonstrate using delegates with static methods, this code also adds a static method with the same signature to Currency:

 struct Currency { public static string GetCurrencyUnit() { return "Dollar"; } 

Now you can use your GetAString instance as follows:

private delegate string GetAString(); static void Main(string[] args) {    int x = 40;    GetAString firstStringMethod = new GetAString(x.ToString);    Console.WriteLine("String is " + firstStringMethod()); Currency balance = new Currency(34, 50); firstStringMethod = new GetAString(balance.ToString); Console.WriteLine("String is " + firstStringMethod()); firstStringMethod = new GetAString(Currency.GetCurrencyUnit); Console.WriteLine("String is " + firstStringMethod()); 

This code shows how you can call a method via a delegate and subsequently reassign the delegate to refer to different methods on different instances of classes, even static methods or methods against instances of different types of class, provided that the signature of each method matches the delegate definition.

However, you still haven't seen the process of actually passing a delegate to another method. Nor have you actually achieved anything particularly useful yet. It is possible to call the ToString() method of int and Currency objects in a much more straightforward way than using delegates! Unfortunately, the nature of delegates requires a fairly complex example before you can really appreciate their usefulness. The next section presents two delegate examples. The first one simply uses delegates to call a coupleof different operations. It illustrates how to pass delegates to methods and how you can use arrays of delegates — although arguably it still doesn't do much that you couldn't do a lot more simply without delegates. Then, a second, much more complex example of a BubbleSorter class is presented, which implements a method to sort out arrays of objects into increasing order. This class would be difficult to write without delegates.




Professional C# 2005
Pro Visual C++ 2005 for C# Developers
ISBN: 1590596080
EAN: 2147483647
Year: 2005
Pages: 351
Authors: Dean C. Wills

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