This post is just notes I am taking from Day 13 in Teach Yourself C# in 21 Days regarding the introduction to delegates in the chapter titled "Making Your Program React with Delegates, Events, and Indexers"
This is a quote from p 445: "A delegate is a reference type that defines the signature for a method call. The delegate can then accept and execute methods that are of the same format as this signature."
In the example program provided for this section, the author creates a function header within a class. The header looks like this:
public delegate void Sort(ref int a, ref int b);
Note also that the delegate has no body within its class.
In addition, another method is defined in the same class:
public void DoSort(Sort ar)
{
ar(ref val1, ref val2);
}
It appears that DoSort is going to be assigned
Further down, another class is defined that includes only two methods, both of which have similar definitions to the delegate Sort definition above and both of which include functioning code, in this case some simple testing and swapping.
The headers differ in that where Sort says delegate, the new class function say static and where Sort says Sort, the new class functions supply their own names. Also the names of the reference parameters are changed.
Here is one of the two method headers defined in a public class called SortProgram
public static void Ascending( ref int first, ref int second)
The methods are void because the arguments are physically swapped as a result of being reference types and that's how the values are returned.
As with many other OOP features, the use of the delegate is not a self evident operation at all. To use the delegate functions you need to instantiate the delegate objects. Here's how the author does it:
Sort up = new Sort(Ascending);
Although this creates an object, the object is not doing an any work. To put the object to work, it must be called by a class object of the type that defines the delegate. In this case, the class that defines the delegate is called SortClass. It is instantiated (SortClass doIT = new SortClass; and initialized SortClass.val1 = 310... and the actual sort is called as a class method in the form doIT.DoSort(up). Seems overly complicated...
If you were to do this without delegates, you probably might need two methods in the main class definition.
The author assets "You could actually get around declaring a doIT object in Line 46 by declaring the DoSort method as static. The DoSort method could then be accessed using the class name instead of an object: SortClass.DoSort(...);"
As an aside here, this technique or trick is presented in an abbreviated form considering the difficulty of the concept and complications of the presentation. The discussion of the features seems to continue in the next section