C# Generic Delegate

In this chapter you will learn:

  1. What is C# Generic Delegate
  2. Syntax to create Generic Delegate
  3. Example for Generic Delegate

Description

A delegate type may contain generic type parameters.

Syntax

For example:


public delegate T Transformer<T> (T arg);

Example

With this definition, we can write a generalized Transform utility method that works on any type:


using System;/*w  ww  .j  av a 2s  .  co m*/
public delegate T Transformer<T> (T arg);

public class Util
{
  public static void Transform<T> (T[] values, Transformer<T> t)
  {
    for (int i = 0; i < values.Length; i++)
      values[i] = t (values[i]);
  }
}

class Test
{
  static void Main()
  {
    int[] values = { 1, 2, 3 };
    Util.Transform (values, Square);      // Dynamically hook in Square
    foreach (int i in values)
      Console.Write (i + "  ");           // 1   4   9
  }

  static int Square (int x) { return x * x; }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What are C# Type Parameters
Home »
  C# Tutorial »
    C# Types »
      C# Generics
C# Generic Types
C# Generic Methods
C# default Generic Value
C# Generic Constraints
C# Subclassing Generic Types
C# Generic Delegate
C# Type Parameters