Can anyone suggest why I cannot cast non-generic delegate to generic with appropriate type parameters? Particularly having two delegates as shown below
public delegate void NotifyCollectionChangedEventHandler(object sender, NotifyCollectionChangedEventArgs e)
public delegate void WeakEventHandler<TSource, TEvent>(TSource sender, TEvent e)
and a delegate variable
NotifyCollectionChangedEventHandler handler;
I can't cast handler to WeakEventHandler<object, NotifyCollectionChangedEventArgs>
. Does anyone know what's the reason for this?
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.
See more on this question at Stackoverflow