-
Notifications
You must be signed in to change notification settings - Fork 1
Add ECS0008 use the null conditional operator for event invocations #48
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add ECS0008 use the null conditional operator for event invocations #48
Conversation
Coverage summary from CodacySee diff coverage on Codacy
Coverage variation details
Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: Diff coverage details
Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: See your quality gate settings Change summary preferencesCodacy stopped sending the deprecated coverage status on June 5th, 2024. Learn more |
) This pull request introduces a new analyzer rule, ECS0008, which is designed to enforce the use of the null-conditional operator when invoking event handlers in C#. This practice helps prevent potential `NullReferenceExceptions`, improving the safety and robustness of the code. Key Features: - **Detection of Potential Violations**: The rule identifies patterns where an event handler is invoked without using the null-conditional operator (`?.Invoke`), such as direct invocations or invocations within an `if` statement checking for `null`. - **Automatic Code Fixes**: The code fix provider automatically replaces the identified pattern with the null-conditional operator, ensuring that the event handler is only invoked when it has subscribers. - **Comprehensive Coverage**: The rule handles cases where the event handler is checked directly and cases where it is first assigned to a local variable. Example Violation: ```csharp public class EventSource { private EventHandler<int> Updated; private int counter; public void RaiseUpdates() { counter++; if (Updated != null) Updated(this, counter); } } ``` Fixed code: ```csharp public class EventSource { private EventHandler<int> Updated; private int counter; public void RaiseUpdates() { counter++; Updated?.Invoke(this, counter); } } ```
This pull request introduces a new analyzer rule, ECS0008, which is designed to enforce the use of the null-conditional operator when invoking event handlers in C#. This practice helps prevent potential
NullReferenceExceptions
, improving the safety and robustness of the code.Key Features:
?.Invoke
), such as direct invocations or invocations within anif
statement checking fornull
.Example Violation:
Fixed code: