CA1009: Correctly declare event handlers?

I have the following event, which users of my class can connect to internal diagnostic messages.

public event EventHandler<string> OutputRaised; 

I raise an event using this function

 protected virtual void OnWriteText(string e) { var handle = this.OutputRaised; if (handle != null) { var message = string.Format("({0}) : {1}", this.Port, e); handle(this, message); } } 

Why am I getting CA1009 correctly declaring event handlers? All the answers that I found do not seem really applicable to my scenario ... Just trying to understand, I do not yet have a real understanding of events and delegates.

Link to CA1009: http://msdn.microsoft.com/en-us/library/ms182133.aspx

+7
c # events
source share
2 answers

According to the "rules", an EventHandler type parameter must inherit from EventArgs:

Event handler methods accept two parameters. The first type of System.Object is called 'sender'. This is the object that raised the event. The second parameter is of type System.EventArgs and is equal to named 'e'. This is event related data. For example, if an event occurs when a file is opened, the event data usually contains the file name.

In your case, it might be something like this:

 public class StringEventArgs : EventArgs { public string Message {get;private set;} public StringEventArgs (string message) { this.Message = message; } } 

and your event handler:

 public event EventHandler<StringEventArgs> OutputRaised; 

When you raise an event, you must disconnect an instance of the StringEventArgs class:

 protected virtual void OnWriteText( string message ) { var handle = this.OutputRaised; if (handle != null) { var message = string.Format("({0}) : {1}", this.Port, e); handle(this, new StringEventArgs(message)); } } 

I would also like to add that theoretically there is nothing wrong with the code. The compiler does not complain, and your code will work. The EventHandler<T> delegate does not indicate that the type parameter should inherit from EventArgs . This FxCop means that you are violating the "design rules" for declaring an event.

+12
source share

Events in .NET usually should contain some derivative from EventArgs , which is not the case with you, I would suggest that the problem.

Define the events to be published in the event:

 public class StringEventArgs : EventArgs { public StringEventArgs(string message) { this.Message = message; } public string Message { get; private set; } } 

Modify your ad and post it:

 public event EventHandler<StringEventArgs> OutputRaised; protected virtual void OnWriteText(string e) { var handle = this.OutputRaised; if (handle != null) { var message = string.Format("({0}) : {1}", this.Port, e); handle(this, new StringEventArgs(message)); } } 
+3
source share

All Articles