Skip to main content

Extension method must be defined in a top level static class

In This Article

CodeRush Classic shows the Extension method must be defined in a top level static class code issue if an extension method is defined in a nested class.

#Fix

Make the class top level or declare the method in another top level static class.

#Purpose

Highlights the extension method declaration statements, which would cause the Extension method must be defined in a top level static class compilation error.

#Example

public static class MyClass
{
    public static class NestedClass
    {
        public static int Total(this int[] intArray)
        {
            int result = 0;
            foreach (int item in intArray)
                result += item;
            return result;
        }   
    }
}

Fix:

public static class MyClass
{
    public static int Total(this int[] intArray)
    {
        int result = 0;
        foreach (int item in intArray)
            result += item;
        return result;
    }   
    public static class NestedClass
    {

    }
}