Cast of parameterized delegate to non parameterized analogue

Can anyone suggest why I cannot cast non-generic delegate to generic with appropriate type parameters? Particularly having two delegates as shown below

  1. public delegate void NotifyCollectionChangedEventHandler(object sender, NotifyCollectionChangedEventArgs e)
  2. public delegate void WeakEventHandler<TSource, TEvent>(TSource sender, TEvent e)

and a delegate variable

  1. NotifyCollectionChangedEventHandler handler;

I can't cast handler to WeakEventHandler<object, NotifyCollectionChangedEventArgs>. Does anyone know what's the reason for this?

Jon Skeet
people
quotationmark

Simply put, they're different types. Imagine you had two classes like this:

public class A1
{
    public int Value { get; set; }
}

public class A2
{
    public int Value { get; set; }
}

They're different classes despite looking equivalent - and you couldn't cast between A1 and A2. It's the same with delegates.

What you can do is wrap the existing delegate:

var weakHandler = new WeakEventHandler<object, NotifyCollectionChangedEventArgs>(handler);

That creates a new delegate that invokes the original delegate when the new delegate is invoked.

people

See more on this question at Stackoverflow