C# Generic delegate

In this chapter you will learn:

  1. delegate with generic type
  2. How to add constraint to delegate generic parameters
  3. Generic Delegate list

Description

delegate can have generic type.


//w  w  w.  j  av a  2 s. c o  m
using System;

delegate void Printer<T>(T t);

class Test
{
    static void consolePrinterInt(int i)
    {
        Console.WriteLine(i);
    }

    static void consolePrinterFloat(float f)
    {
        Console.WriteLine(f);
    }
    static void Main()
    {
        Printer<int> p = consolePrinterInt;

        p(2);

    }
}

The code above generates the following result.

Parameter constaints

How to add constraint to delegate generic parameters


using System;/*  ww w . j  av a 2 s.c o m*/

public delegate R Operation<T1, T2, R>( T1 val1, T2 val2 )
    where T1: struct
    where T2: struct
    where R:  struct;

public class MainClass
{
    public static double Add( int val1, float val2 ) {
        return val1 + val2;
    }

    static void Main() {
        Operation<int, float, double> op = new Operation<int, float, double>( Add );

        Console.WriteLine( "{0} + {1} = {2}", 1, 3.2, op(1, 3.2f) );
    }
}

The code above generates the following result.

Generic Delegate list

Generic Delegate list


using System;/* w  ww  . j a  v  a2  s  .com*/
using System.Collections.Generic;

public delegate void MyDelegate<T>( T i );

public class DelegateList<T>
{
    public void Add( MyDelegate<T> del ) {
        imp.Add( del );
    }

    public void CallDelegates( T k ) {
        foreach( MyDelegate<T> del in imp ) {
            del( k );
        }
    }

    private List<MyDelegate<T> > imp = new List<MyDelegate<T> >();
}

public class MainClass
{
    static void Main() {
        DelegateList<int> delegates = new DelegateList<int>();

        delegates.Add( PrintInt );
        delegates.CallDelegates( 42 );
    }

    static void PrintInt( int i ) {
        Console.WriteLine( i );
    }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Func and Action from system namespace
  2. Example for C# Func and Action
Home »
  C# Tutorial »
    C# Types »
      C# Delegate
C# Delegate
C# Multicast Delegates
delegate parameters
C# Generic delegate
C# Func and Action
C# Anonymous delegate