S4226 — Extensions should be in separate namespaces

Language
C#
Type
Code smell
Severity
Minor
Tags
confusing

Why is this an issue?

It makes little sense to create an extension method when it is possible to just add that method to the class itself.

This rule raises an issue when an extension is declared in the same namespace as the class it is extending.

Noncompliant code example


namespace MyLibrary
{
    public class Foo
    {
        // ...
    }

    public static class MyExtensions
    {
        public static void Bar(this Foo a) // Noncompliant
        {
            // ...
        }
    }
}

Compliant solution

Using separate namespace:


namespace MyLibrary
{
    public class Foo
    {
        // ...
    }
}

namespace Helpers
{
    public static class MyExtensions
    {
        public static void Bar(this Foo a)
        {
            // ...
        }
    }
}

Merging the method in the class:


namespace MyLibrary
{
    public class Foo
    {
        // ...
        public void Bar()
        {
            // ...
        }
    }
}

Exceptions

↑ Back to top