0

I've got a problem with an event rising. Here is my base class:

public abstract class MyClass<T>
{
  public event EventHandler<MessageReceivedEventArgs<T>> MessageReceived;

  protected void OnMessageReceived(MyClass<T> sender, MessageReceivedEventArgs<T> e)
  {
    EventHandler<MessageReceivedEventArgs<T>> handler = MessageReceived;

    if (MessageReceived != null)
      MessageReceived(sender, e);
  }
}

And my implementation :

public class MyDerivedClass: MyClass<string>
{
  void AFunction()
  {
    // Do some stuff
    OnMessageReceived(this, new MessageReceivedEventArgs<string>("data"));
  }

When OnMessageReceived is called, the system throw a System.ArgumentNullException ("Value cannot be null. Parameter name: type"). I already read this thread, and this one too, which help me to construct this code. But I can't find the reason of these exception (sender and e are not null, checked with the debugger).

What am I doing wrong ?

EDIT : Here's my MessageReceivedEventArgs implementation :

public class MessageReceivedEventArgs<T> : EventArgs
{
  public T Data { get; private set; }

  public MessageReceivedEventArgs(T data)
  {
    Data = data;
  }
}
Community
  • 1
  • 1
Nicolas Voron
  • 2,916
  • 1
  • 21
  • 35
  • can you add MessageReceivedEventArgs class in the code? The constructor of MessageReceivedEventArgs should accept a string. Is it doing that? What compile time error are u getting? – Rockstart Oct 26 '12 at 10:45
  • @Rockstart I edited my post. The constructor accept T as it's generic. The compile time error is "Value cannot be null. Parameter name: type". Thanks :) – Nicolas Voron Oct 26 '12 at 10:52

1 Answers1

3

Are you sure the Exception is thrown by your code? It could be possible that any of the event subscribers throws the Exception.

Event handling is a sequential operation. So if the first subscriber throws an unhandled exception the event handling will fail.

Edit: Have you had a look at the stacktrace. Also you could try to let the ide stop on every ArgumentNullException via the "Exception" window.

Benjamin
  • 120
  • 1
  • 7
  • I feel so stupid... I was convinced that it was related to the generic type and the inheritance, and it was just as you said, a problem with a suscriber. My event rising was in a try-catch, and I didn't know that raising an event can throw an exception if one event subscribers call failed. Thanks a lot Benjamin ! :D – Nicolas Voron Oct 26 '12 at 11:00