Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Can we create extension method in non static class C#?

Yes. It is compulsion that the Extension method must be in a Static class only so that only one Instance is created.


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.

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


Add keyword static to class declaration:

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

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.