Error: extension method must be defined in nonequivalent static class

I get the following compilation error in the class name.

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

I do not use a regular class. What could be the reason for this. I do not know and do not want to use extension methods.

+6
source share
6 answers

As requested, here is my comment as an answer:

Without your code, we can do little. It’s best to assume that you accidentally typed β€œthis” somewhere in the parameter list.

+39
source

Example for extension method

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

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" from the method parameter.

+3
source

I assume this refers to your previous list of questions ; if so, then the example I provided is an extension method and will 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 have to match the consumption class, but extension methods are how you can use it as list.Reverse()

If you do not want this to be an extension method, you can simply make it a local static method - just take "this" from the first parameter:

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

and use as:

 foreach(var val in Reverse(list)) {...} 
+1
source

When creating an extension method, the following points should be considered:

  • The class that defines the extension method should not be general, but static
  • Each extension method must be a static method.
  • The first parameter of the extension method should use the this .
0
source

How about sending the code? Extension methods are declared preceding the first parameter of the static method with this. Since you will not use the extension method, I suspect that you accidentally ran the parameter list with this .

Look for something like:

 void Method(this SomeType name) { } 
0
source

Source: https://habr.com/ru/post/901887/


All Articles