I want to raise an event that will allow an object of type Widget (or any derived class) to be returned, with the specific type being defined via generics.
public class WidgetProcessor
{
public event EventHandler<WidgetRequiredEventArgs<Widget>> WidgetRequired;
public void DoSomethingThatNeedsAWidget<T>() where T: Widget
{
Widget widget = OnWidgetRequired<T>();
//...now do something with the widget
}
private T OnWidgetRequired<T>() where T: Widget
{
T widget = null;
if (this.WidgetRequired != null)
{
WidgetRequiredEventArgs<T> e = new WidgetRequiredEventArgs<T>();
this.WidgetRequired(this, e);
widget = e.Widget;
}
return widget;
}
}
public class WidgetRequiredEventArgs<T>
: EventArgs where T : Widget
{
public WidgetRequiredEventArgs()
{
}
public T Widget { get; set; }
}
Constraints on OnWidgetRequired<T>() and DoSomethingThatNeedsAWidget<T>() allow me to limit the specified type to Widget or a derived class. Ideally, I'd do the same for the event declaration, but it doesn't support the use of <T> with a constraint for the event args, so I've had to declare it explicitly as Widget.
However, this gives the compile-time error:
CS1503: Argument 2: cannot convert from 'WidgetRequiredEventArgs<T>' to 'WidgetRequiredEventArgs<Widget>'
for the e argument on the line:
this.WidgetRequired(this, e);
So why don't the constraints on OnWidgetRequired<T>() and WidgetRequiredEventArgs<T> satisfy the eventhandler's type definition, and how can I get it to compile?