I have an event:
public event RoutedEventHandler ActionEvent;
I have a superclass:
internal class MyEventArgs : RoutedEventArgs
{
public enum SomeAction
{
ACTION1,
ACTION2,
ACTION3
}
public MyEvent(SomeAction action)
{
this.action = action;
}
public SomeAction action;
}
I call the function:
private void onAction(object sender, MyEventArgs args) { if (ActionEvent != null) ActionEvent(sender, args); }
And finally, hence my question, I cast inside the called method:
void ActionEvent(object sender, RoutedEventArgs e)
{
MyEvent args = (MyEvent)e;
}
Is this legal? Can I avoid introducing delegates? It compiles and runs happily in debug mode.
(I'm new in C#. I have been using C++ for ages. The answer would be a definite yes in C++, but I want to double check that I can do this in C# as well without introducing "hidden" stability problems, multi-threading problems or anything like that. In fact, C# should warn me in real-time if I used a wrong cast, but just I asked just to double check.)
You can do this - but then you're really being very specific in your implementation, without being specific in the type system.
Why not just use EventHandler<TEventArgs>
?
public event EventHandler<MyEventArgs> ActionEvent;
Then:
void ActionEvent(object sender, MyEventArgs e)
{
...
}
See more on this question at Stackoverflow