Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method must be defined in non-generic static class

Tags:

Error at:

public partial class Form2 : Form 

Probable cause:

public static IChromosome To<T>(this string text) {     return (IChromosome)Convert.ChangeType(text, typeof(T)); } 

Attempted (without static keyword):

public IChromosome To<T>(this string text) {     return (IChromosome)Convert.ChangeType(text, typeof(T)); } 
like image 744
Sameer Avatar asked May 02 '12 10:05

Sameer


People also ask

Can we define extension methods for static class?

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter is preceded by the this modifier.

Can extension methods be non static?

Actually I'm answering the question of why extension methods cannot work with static classes. The answer is because extension methods are compiled into static methods that cannot recieve a reference to a static class.

Can we define extension method for a class which itself is a static class not?

No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.

Are extension methods always static?

Here, this keyword is used for binding, Geek is the class name in which you want to bind, and g is the parameter name. Extension methods are always defined as a static method, but when they are bound with any class or structure they will convert into non-static methods.


2 Answers

If you remove "this" from your parameters it should work.

public static IChromosome To<T>(this string text) 

should be:

public static IChromosome To<T>(string text) 
like image 122
imPrettyAwesomeLikeThat Avatar answered Sep 28 '22 10:09

imPrettyAwesomeLikeThat


The class containing the extension must be static. Yours are in:

public partial class Form2 : Form 

which is not a static class.

You need to create a class like so:

static class ExtensionHelpers {     public static IChromosome To<T>(this string text)      {          return (IChromosome)Convert.ChangeType(text, typeof(T));      }  } 

To contain the extension methods.

like image 37
DaveShaw Avatar answered Sep 28 '22 10:09

DaveShaw