0

How to create extension method for a generic type?

The below code returning error

Extension method can only be declared in non-generic, non-nested static class

Code:

public static class PagedList<T> where T : BaseEntity
{
    public static IEnumerable<T> ToPagedList(this IEnumerable<T> source, int pageNumber = 0, int pageSize = 5)
    {
        return source.Skip(pageNumber * pageSize).Take(pageSize);
    }
}

Any further implementation with this makes this work ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • possible duplicate of [Why is it impossible to declare extension methods in a generic static class?](http://stackoverflow.com/questions/2618271/why-is-it-impossible-to-declare-extension-methods-in-a-generic-static-class) – Tom Blodget Oct 25 '14 at 13:33

2 Answers2

2

Specify generic types directly on the method and make the class as the error says static and non-generic.

public static class PagedList
{
    public static IEnumerable<T> ToPagedList<T>(this IEnumerable<T> source, 
        int pageNumber = 0, int pageSize = 5) where T : BaseEntity
    {
        return source.Skip(pageNumber * pageSize).Take(pageSize);
    }
}
Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
0

You should listen the error message, you need to declare your extension method inside of a non-generic class.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184