Convert event to use generic delegate : Generic delegate « Generics « C# / C Sharp






Convert event to use generic delegate

Convert event to use generic delegate
/*
Example code from 


Chapter 18 - Generics
C# 2.0: The Complete Reference, Second Edition
by Herbert Schildt 
McGraw-Hill/Osborne ? 2006
*/       
       
using System;

class MyEventArgs : EventArgs {
  public int eventnum;
}

delegate void MyEventHandler<T, V>(T source, V args);

class MyEvent {
  static int count = 0;

  public event MyEventHandler<MyEvent, MyEventArgs> SomeEvent;

  public void OnSomeEvent() {
    MyEventArgs arg = new MyEventArgs();

    if(SomeEvent != null) {
      arg.eventnum = count++;
      SomeEvent(this, arg);
    }
  }
}

class X {
  public void handler<T, V>(T source, V arg) where V : MyEventArgs {
    Console.WriteLine("Event " + arg.eventnum + " received by an X object.");
    Console.WriteLine("Source is " + source);
    Console.WriteLine();
  }
}

class Y {
  public void handler<T,V>(T source, V arg) where V : MyEventArgs {
    Console.WriteLine("Event " + arg.eventnum + " received by a Y object.");
    Console.WriteLine("Source is " + source);
    Console.WriteLine();
  }
}

class Test {
  public static void Main() {
    X ob1 = new X();
    Y ob2 = new Y();
    MyEvent evt = new MyEvent();

    evt.SomeEvent += ob1.handler;
    evt.SomeEvent += ob2.handler;

    evt.OnSomeEvent();
    evt.OnSomeEvent();
  }
}

           
       








Related examples in the same category

1.A simple generic delegateA simple generic delegate
2.Generic Delegate and non-generic delegate
3.Generics and Delegates
4.a generic delegate being initialized with a normal method
5.Generic Anonymous Methods