Why can't I directly pass a custom event args class into a method subscribing to my event?
.net, c#, events
Solution
Instead of declaring your event as being of type `EventHandler`, create a new delegate that specifically uses your custom event args class:
public delegate void MyEventHandler(object sender, MyEventArgs args);
public event MyEventHandler MyEvent;
Now you can pass the arguments directly without casting.
The other option is to use the generic `EventHandler<T>`:
public event EventHandler<MyEventArgs> MyEvent;
I prefer the former, since you can then give the delegate type a more descriptive name, though the latter is a bit quicker.
Problem
Why can't I directly pass custom event arguments into a method subscribing to my event even though my custom event args class directly inherits from `EventArgs`? For example, consider the two below classes. One is the class I want to work with, the other inherits from `EventArgs`, and contains some additional information related to the event: ``` using System; namespace ConsoleApplication11 { class MyClass { public event EventHandler MyEvent; public void MyMethod(int myNumber) { Console.WriteLine(myNumber); if(myNumber == 7) { MyEvent.Invoke(null, new MyCustomEvent() { Foo = "Bar" }); } } } class MyCustomEvent : EventArgs { public string Foo { get; set; } } } ``` So if a number 7 is passed into `MyMethod`, I want to invoke `MyEvent` passing in the a new instance of the `MyCustomEvent` class to any method subscribing to my event. I subscribe to this from my main program like so: ``` using System; namespace ConsoleApplication11 { class Program { static void Main(string[] args) { MyClass myClass = new MyClass(); myClass.MyEvent += new EventHandler(myClass_MyEvent); for (int i = 0; i < 9; i++) { myClass.MyMethod(i); } } static void myClass_MyEvent(object sender, EventArgs e) { //Do Stuff } } } ``` Even though I am passing in a `MyCustomEvent` object when invoking the event, if I change the second parameter in the method subscribing to my event to a `MyCustomEvent` object I get a compile error. I need to instead explicitly cast the `EventArgs` object to a `MyCustomEvent` before I can access any additional fields/methods etc inside the class. When working with an object that has a lot of different events, each one having a unique related custom `EventArgs` class, keeping track of what the EventArgs in each method subscribing to each event needs to be casted to can get a bit messy. It would be a lot easier if I could pass my custom EventArgs class directly into the methods subscribing to my event. Is this a possibility? Thanks