83 lines
1.5 KiB
Plaintext
83 lines
1.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Since .Net Framework version 2.0 it is not necessary to declare a delegate that specifies a class derived from ``++System.EventArgs++``. The ``++System.EventHandler<TEventArgs>++`` delegate mechanism should be used instead as it allows any class derived from ``++EventArgs++`` to be used with that handler.
|
|
|
|
|
|
This rule raises an issue when an old style delegate is used as an event handler.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,text]
|
|
----
|
|
public class MyEventArgs : EventArgs
|
|
{
|
|
}
|
|
|
|
public delegate void MyEventHandler(object sender, MyEventArgs e); // Noncompliant
|
|
|
|
public class EventProducer
|
|
{
|
|
public event MyEventHandler MyEvent;
|
|
|
|
protected virtual void OnMyEvent(MyEventArgs e)
|
|
{
|
|
if (MyEvent != null)
|
|
{
|
|
MyEvent(e);
|
|
}
|
|
}
|
|
}
|
|
|
|
public class EventConsumer
|
|
{
|
|
public EventConsumer(EventProducer producer)
|
|
{
|
|
producer.MyEvent += HandleEvent;
|
|
}
|
|
|
|
private void HandleEvent(object sender, MyEventArgs e)
|
|
{
|
|
// Do something...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,text]
|
|
----
|
|
public class MyEventArgs : EventArgs
|
|
{
|
|
}
|
|
|
|
public class EventProducer
|
|
{
|
|
public event EventHandler<MyEventArgs> MyEvent;
|
|
|
|
protected virtual void OnMyEvent(MyEventArgs e)
|
|
{
|
|
if (MyEvent != null)
|
|
{
|
|
MyEvent(e);
|
|
}
|
|
}
|
|
}
|
|
|
|
public class EventConsumer
|
|
{
|
|
public EventConsumer(EventProducer producer)
|
|
{
|
|
producer.MyEvent += HandleEvent;
|
|
}
|
|
|
|
private void HandleEvent(object sender, MyEventArgs e)
|
|
{
|
|
// Do something...
|
|
}
|
|
}
|
|
----
|
|
|
|
|