C# Generic delegate

Description

delegate can have generic type.


/*from   ww w  . j  a  v  a 2 s.  com*/
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;/*from  w w w  .  j a  v  a2s . 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;/*from  w  w w . j  av  a  2  s . c om*/
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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor