tags:

views:

74

answers:

2

Hello,

Is it possible to create a list containing delegates of different types ? For example considere this two delegates :

class MyEventArg1 : EventArgs {}
class MyEventArg2 : EventArgs {}

EventHandler<MyEventArgs1> handler1;
EventHandler<MyEventArgs2> handler2;

I would like to do something like that :

List<EventHandler<EventArgs>> handlers = new List<EventHandler<EventArgs>>();

handlers.Add((EventHandler<EventArgs>)handler1);
handlers.Add((EventHandler<EventArgs>)handler2);

But the cast from one delegate to another seems not possible. My goal is to store the delegates in a list not to call them; but just to unregister them automaticly.

Thanks

+1  A: 

You will be able to do this in C# 4.0 thanks to the generics variance but until then you need to find another way (maybe ArrayList).

Darin Dimitrov
+1  A: 

Yes, this doesn't work, the delegates are completely unrelated types. Normally, generic types would have only System.Object as the common base type. But here, since they are delegates, you could store them in a List<Delegate>. I doubt that's going to help you getting them unregistered though. But I can't really envision what that code might look like.

Hans Passant