[c#] Extension methods must be defined in a non-generic static class

I'm getting the error:

Extension methods must be defined in a non-generic static class

On the line:

public class LinqHelper

Here is the helper class, based on Mark Gavells code. I'm really confused as to what this error means as I am sure it was working fine when I left it on Friday!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Expressions;
using System.Reflection;

/// <summary>
/// Helper methods for link
/// </summary>
public class LinqHelper
{
    public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
    {
        return ApplyOrder<T>(source, property, "OrderBy");
    }
    public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
    {
        return ApplyOrder<T>(source, property, "OrderByDescending");
    }
    public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
    {
        return ApplyOrder<T>(source, property, "ThenBy");
    }
    public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
    {
        return ApplyOrder<T>(source, property, "ThenByDescending");
    }
    static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
    {
        string[] props = property.Split('.');
        Type type = typeof(T);
        ParameterExpression arg = Expression.Parameter(type, "x");
        Expression expr = arg;
        foreach (string prop in props)
        {
            // use reflection (not ComponentModel) to mirror LINQ
            PropertyInfo pi = type.GetProperty(prop);
            expr = Expression.Property(expr, pi);
            type = pi.PropertyType;
        }
        Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
        LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

        object result = typeof(Queryable).GetMethods().Single(
                method => method.Name == methodName
                        && method.IsGenericMethodDefinition
                        && method.GetGenericArguments().Length == 2
                        && method.GetParameters().Length == 2)
                .MakeGenericMethod(typeof(T), type)
                .Invoke(null, new object[] { source, lambda });
        return (IOrderedQueryable<T>)result;
    }
}

This question is related to c# .net linq extension-methods compiler-errors

The answer is


change

public class LinqHelper

to

public static class LinqHelper

Following points need to be considered when creating an extension method:

  1. The class which defines an extension method must be non-generic, static and non-nested
  2. Every extension method must be a static method
  3. The first parameter of the extension method should use the this keyword.

I encountered a similar issue, I created a 'foo' folder and created a "class" inside foo, then I get the aforementioned error. One fix is to add "static" as earlier mentioned to the class which will be "public static class LinqHelper".

My assumption is that when you create a class inside the foo folder it regards it as an extension class, hence the following inter alia rule apply to it:

1) Every extension method must be a static method

WORKAROUND If you don't want static. My workaround was to create a class directly under the namespace and then drag it to the "foo" folder.


A work-around for people who are experiencing a bug like Nathan:

The on-the-fly compiler seems to have a problem with this Extension Method error... adding static didn't help me either.

I'd like to know what causes the bug?

But the work-around is to write a new Extension class (not nested) even in same file and re-build.

Figured that this thread is getting enough views that it's worth passing on (the limited) solution I found. Most people probably tried adding 'static' before google-ing for a solution! and I didn't see this work-around fix anywhere else.


Extension method should be inside a static class. So please add your extension method inside a static class.

so for example it should be like this

public static class myclass
    {
        public static Byte[] ToByteArray(this Stream stream)
        {
            Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
            Byte[] buffer = new Byte[length];
            stream.Read(buffer, 0, length);
            return buffer;
        }

    }

Try changing it to static class and back. That might resolve visual studio complaining when it's a false positive.


if you do not intend to have static functions just get rid of the "this" keyword in the arguments.


Try changing

public class LinqHelper

to

 public static class LinqHelper

Change it to

public static class LinqHelper

Add keyword static to class declaration:

// this is a non-generic static class
public static class LinqHelper
{
}

I was scratching my head with this compiler error. My class was not an extension method, was working perfectly since months and needed to stay non-static. I had included a new method inside the class:

private static string TrimNL(this string Value)
{...}

I had copied the method from a sample and didn't notice the "this" modifier in the method signature, which is used in extension methods. Removing it solved the issue.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to extension-methods

The operation cannot be completed because the DbContext has been disposed error Extension methods must be defined in a non-generic static class Java equivalent to C# extension methods Razor HtmlHelper Extensions (or other namespaces for views) Not Found Mocking Extension Methods with Moq AddRange to a Collection Distinct() with lambda? Convert string[] to int[] in one line of code using LINQ How do I extend a class with c# extension methods? Static extension methods

Examples related to compiler-errors

intellij idea - Error: java: invalid source release 1.9 Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug' Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error Android java.exe finished with non-zero exit value 1 error: expected primary-expression before ')' token (C) What does "collect2: error: ld returned 1 exit status" mean? Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing Maven error :Perhaps you are running on a JRE rather than a JDK? What does a "Cannot find symbol" or "Cannot resolve symbol" error mean? Operator overloading ==, !=, Equals