smatter
smatter

Reputation: 29168

Error: Extension method must be defined in a non-generic static class

I get the following compilation error at the class name.

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

I am not using normal class. What could be the reason for this. I don't know and don't want to use extension methods.

Upvotes: 7

Views: 26463

Answers (6)

Alberto Madrid
Alberto Madrid

Reputation: 31

I had the same problem, and solved it as follows. My code was something like this:

public static class ExtensionMethods 
{
    public static object ToAnOtherObject(this object obj) 
    {
        // Your operation here
    }
}

and I changed it to

public static class ExtensionMethods 
{
    public static object ToAnOtherObject(object obj) 
    {
        // Your operation here
    }
}

I removed the word "this" of the parameter of the method.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062502

I'm guessing this relates to your previous list question; if so, the example I provided is an extension method, and would be:

public static class LinkedListUtils { // name doesn't matter, but must be
                                      // static and non-generic
    public static IEnumerable<T> Reverse<T>(this LinkedList<T> list) {...}
}

This utility class does not need to be the same as the consuming class, but extension methods is how it is possible to use as list.Reverse()

If you don't want it as an extension method, you can just make it a local static method - just take away the "this" from the firstparameter:

public static IEnumerable<T> Reverse<T>(LinkedList<T> list) {...}

and use as:

foreach(var val in Reverse(list)) {...}

Upvotes: 1

Peter PAD
Peter PAD

Reputation: 2310

Sample for extension method

public static class ExtensionMethods {
 public static object ToAnOtherObject(this object obj) {
  // Your operation here
 }
}

Upvotes: 5

Jules
Jules

Reputation: 6346

As requested, here is my comment as an answer:

Without your code there isn't much we can do. My best guess is that you accidentally typed "this" somewhere in a parameter list.

Upvotes: 43

CodesInChaos
CodesInChaos

Reputation: 108790

How about posting your code? Extension methods are declared by preceding the first parameter of a static method with this. Since you don't won't to use an extension method, I suspect you accidentally started a parameter list with this.

Look for something like:

void Method(this SomeType name)
{
}

Upvotes: 0

Glory Raj
Glory Raj

Reputation: 17691

The following points need to be considered when creating an extension method:

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

Upvotes: 0

Related Questions