All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S3244.html Maven / Gradle / Ivy

There is a newer version: 9.30.0.95878
Show newest version

Why is this an issue?

When working with anonymous functions, it is important to keep in mind that each time you create one, it is a completely new instance.

In this example, even though the same lambda expression is used, the expressions are stored separately in the memory and are therefore not equal or the same.

Func<int, int> lambda1 = x => x + 1;
Func<int, int> lambda2 = x => x + 1;

var result = lambda1 == lambda2; // result is false here

This is even more true when working with events since they are multicast delegates that offer ways of subscribing and unsubscribing to them. If an anonymous function is used to subscribe to an event, it is impossible to unsubscribe from it. This happens because to remove the entry from the subscription list, a reference to the original method is needed, but if the anonymous function has not been stored before subscribing, there is no way to find a reference to it.

Instead, store the callback to a variable or a named method and use the variable or method to subscribe and unsubscribe.

How to fix it

Store the callback to a variable or a named method and use the variable or method to subscribe and unsubscribe.

Code examples

Noncompliant code example

event EventHandler myEvent;

void DoWork()
{
        myEvent += (s, e) => Console.WriteLine($"Event raised with sender {s} and arguments {e}!");
        // ...
        myEvent -= (s, e) => Console.WriteLine($"Event raised with sender {s} and arguments {e}!"); // Noncompliant: this callback was never subscribed
}

Compliant solution

event EventHandler myEvent;
void LogEvent(object s, EventArgs e) => Console.WriteLine($"Event raised with sender {s} and arguments {e}!");

void DoWork()
{
        myEvent += LogEvent;
        // ...
        myEvent -= LogEvent; // Compliant: LogEvent points to the same callback used for subscribing
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy