Dev Guy

Dev Guy

Friday, August 15, 2014

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


Goal 

You are creating a c# or vb.net program and when you try to compile you get an "Extension method must be defined in a non-generic static class". This happens to you, for instance if you are creating a windows service in c# and you just keep adding voids and functions to you main class in the namespace of the project.  It can be any type of project I don’t mean to pick on windows services.

Environment

Windows 7 64 bit and Visual Studio 2010.

Issue

            In my case I added many public static functions to my main class which is of course not static. Static voids or functions need to belong to a static class.            

 

Resolution                                             

            Add a class to your project. Make the class you create a public static class. Cut and paste your static voids and functions in.  Reference your voids and subs using the syntax: ClassName.FuntionorVoid();

            For example in my project I have a bunch of c# functions that do vb.net functions like right. I created a public static class called DataChecks. The syntax to call it from my main class is below:

         fields[7] = "0." + DataChecks.Right("00" + fields[7].ToString().Trim(), 2);

                                      

            Because it is public and static you can just reference it anywhere in the namespace using classname.voidorfunction. If it were not static public you would need to:

 

            ClassName myname = new ClassName();

            Myname.voidoffunction();

 
         Either way, the moral of the lesson is not to mix statics and non-statics.
 

Conclusion 

 

If you are like me, it is easy to want to get a project done quickly and forget some basic tenets, like you can’t put statics in a regular class. This will cost you debug time. You should break out your project in meaningful classes anyway, its just good practice.