C# Generic Delegate
In this chapter you will learn:
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: