18.1. Using Delegates

Listing 18.1 shows a simple delegate.

Listing 18.1. A Simple Delegate Example (C#)
1 using System;
2 public class Test {
3   public delegate float CalcIncome(float hourlyWages);
4   public static void Main(string[] args) {
      CalcIncome del = new
      CalcIncome(Person.CalcAnnualIncome);
      Console.WriteLine(del(26));
5   }
6   public class Person {
7   public float income;
8   public static float CalcMonthlyIncome(float hourlyWages) {
      return hourlyWages * 160;
9   }
10  public static float CalcAnnualIncome(float hourlyWages) {
        resturn hourlyWages * 160 * 12;
11  }
12}

The first step is to declare the delegate, which is done in line 3:

public delegate float CalcIncome(float hourlyWages);

This declares a public delegate called CalcIncome that takes a float as a parameter and returns a float as a result.

The entry point instantiates the delegate using the following line:

CalcIncome del = new CalcIncome(Person.CalcAnnualIncome);

Note that when you instantiate a delegate you must essentially pass the name of the function that matches the signature of the delegate—that is, the name of the function that will actually get called after the delegate is activated. A delegate is like a function pointer; in the preceding line we are simply getting a reference del to a function pointer pointing to the function Person.CalcAnnualIncome. This function can be any function as long as its signature matches that of the delegate (takes a float and returns a float). The Person.CalcAnnualIncome and Person.CalcMonthlyIncome methods are both defined in a separate Person class. Note that these two methods do not have to be static.

The following line invokes the delegate:

Console.WriteLine(del(26));

Essentially the runtime passes the argument 26 to the actual function wrapped by our delegate del, which is Person.CalcAnnualIncome, and then calls that method. This returns the value, which is then printed as 49920.

This is the gist of delegates.

At this point you may wonder how delegates handle exceptions thrown by the underlying method they are pointing to. Listing 18.2 answers that question.

Listing 18.2. Exception Handling in Delegates (C#)
using System;

public class Test {

  public delegate float CalcIncome(string hourlyWages);

  public static void Main(string[] args) {
    CalcIncome del = new CalcIncome(Person.CalcAnnualIncome);
    Console.WriteLine(del("hghg"));
  }
}

public class Person {

  public float income;
  public static float CalcMonthlyIncome(string hourlyWages) {
    return (float) Double.Parse(hourlyWages) * 160;
  }
  public static float CalcAnnualIncome(string hourlyWages) {
    return (float) Double.Parse(hourlyWages) * 160 * 12;
  }
}

In Listing 18.2 the delegate is modified to accept a string instead of a float as a parameter. Passing an invalid numeric string causes a System.FormatException, which is then thrown by the CLR.

Delegates can be packaged as properties or static members of a class. In the previous listings the delegate was an instance member of the Test class. Listing 18.3 shows delegates as static read-only members of the Test class.

Listing 18.3. Delegates as static Members (C#)
using System;

public class Test {

  public delegate float CalcIncome(float hourlyWages);

  public static readonly CalcIncome MonthlyIncome = new
                          CalcIncome(Person.CalcMonthlyIncome);

  public static readonly CalcIncome AnnualIncome = new
                           CalcIncome(Person.CalcAnnualIncome);

  public static void Main(string[] args) {

    try {
      Console.WriteLine(Test.MonthlyIncome(40));
      Console.WriteLine(Test.AnnualIncome(40));
    } catch(Exception e) {
      Console.WriteLine(e.StackTrace);
    }
  }
}

public class Person {

  public float income;

  public static float CalcMonthlyIncome(float hourlyWages) {
    return hourlyWages * 160;
  }
  public static float CalcAnnualIncome(float hourlyWages) {
    return hourlyWages * 160 * 12;
  }
}

In Listing 18.3, the delegates are created as two static members (MonthlyIncome and AnnualIncome), and these are invoked.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.233.41