Skip to content

NET-2668 Fix S3398 FP: On private methods in C#14 extensions classes #9773

@manfred-brands

Description

@manfred-brands

Description

When an C#14 extension method calls a private static function declared inside the class, but outside the extension block, S3398 is raised.

If the private method is moved inside the extension block, it raises IDE0051 (Member not used) because this will create an extension method for that private method which cannot be used.
The compiler also outputs 2 instances of that method, one as the non-accessible extension, the other as a static method in the outer class.

Reproducer

namespace System
{
    /// <summary>
    /// Extension methods for <see cref="ArgumentNullException"/>.
    /// </summary>
    public static class ArgumentNullExceptionExtensions
    {
        extension(ArgumentNullException)
        {
            /// <summary>Throws an <see cref="ArgumentNullException"/> if <paramref name="argument"/> is null.</summary>
            /// <param name="argument">The reference type argument to validate as non-null.</param>
            /// <param name="paramName">The name of the parameter with which <paramref name="argument"/> corresponds.</param>
            public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null)
            {
                if (argument is null)
                {
                    ThrowArgumentNullException(paramName);
                }
            }
        }

        [DoesNotReturn]
        private static void ThrowArgumentNullException(string? paramName) =>
            throw new ArgumentNullException(paramName);
    }
}

Product and Version

NuGet SonarAnalyzer.CSharp version 10.15.0.120848

Metadata

Metadata

Assignees

No one assigned

    Labels

    False PositiveRule IS triggered when it shouldn't be.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions