org.sonar.plugins.csharp.S3908.html Maven / Gradle / Ivy
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
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
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...
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy