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

Get .NET for Java Developers: Migrating to C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.