rjmurillo / EffectiveCSharp.Analyzers

Many of the recommendations in the book Effective C#: 50 Specific Ways to Improve Your C# can be validated by Roslyn-based analyzers and code fixes.
MIT License
2 stars 1 forks source link

Add ECS0008 use the null conditional operator for event invocations #48

Closed rjmurillo closed 2 months ago

rjmurillo commented 2 months ago

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:

Example Violation:

public class EventSource
{
    private EventHandler<int> Updated;
    private int counter;

    public void RaiseUpdates()
    {
        counter++;
        if (Updated != null)
            Updated(this, counter);
    }
}

Fixed code:

public class EventSource
{
    private EventHandler<int> Updated;
    private int counter;

    public void RaiseUpdates()
    {
        counter++;
        Updated?.Invoke(this, counter);
    }
}
codacy-production[bot] commented 2 months ago

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
:white_check_mark: +2.62% (target: -1.00%) :white_check_mark: 95.62%
Coverage variation details | | Coverable lines | Covered lines | Coverage | | ------------- | ------------- | ------------- | ------------- | | Common ancestor commit (a98a3388b9638d1b104e8df36501a3d80436d42a) | 531 | 440 | 82.86% | | | Head commit (0bec5600e930bdd94c1ada38c4b8e18a5249e76d) | 668 (+137) | 571 (+131) | 85.48% (**+2.62%**) | **Coverage variation** is the difference between the coverage for the head and common ancestor commits of the pull request branch: ` - `
Diff coverage details | | Coverable lines | Covered lines | Diff coverage | | ------------- | ------------- | ------------- | ------------- | | Pull request (#48) | 137 | 131 | **95.62%** | **Diff coverage** is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: `/ * 100%`

See your quality gate settings    Change summary preferences

Codacy stopped sending the deprecated coverage status on June 5th, 2024. Learn more