Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the extract method command in visual studio create static methods?

Why does Visual Studio by default create a private static method when refactoring code and selecting extract method?

If I'm refactoring a non-static class and the method is only visible within the class why is it static?

Is there some performance benefit by calling a private static method within a non-static class compared to a non-static method within a non-static class?

Is it for readability to simply show that the method does not rely on any member variables of the class?

like image 940
Crippeoblade Avatar asked Feb 04 '09 12:02

Crippeoblade


People also ask

Why is a method made static?

No object exists before main. So main must be invoked without any object Hence main is declared as a "static member" function, because static functions can be called without any object. If you declare a method as static then you don't have to call it by creating an object of the class.

What is extract method in C#?

Extract Method refactoring is a process of improving the structure of code by creating a new method from an existing code block, and replacing the original code block with a call to the new method. This improves the readability and maintainability of the code.

What is Extract method refactoring?

The Extract Method refactoring lets you take a code fragment that can be grouped, move it into a separated method, and replace the old code with a call to the method.


2 Answers

Why does Visual Studio by default create a private static method when refactoring code and selecting extract method?

It does this only if your method doesn't access any member variables/methods/properties. This is good because it basically operates on the principle of least assumptions: since you don't access instance-specific data, might as well make the method static.

Is there some performance benefit by calling a private static method within a non-static class compared to a non-static method within a non-static class?

Theoretically, there might be but I doubt it. However, making the method static makes it clear that it will not access or modify instance data, which I find a useful hint.

like image 87
Konrad Rudolph Avatar answered Sep 21 '22 06:09

Konrad Rudolph


Creating a static method may be considered a performance enhancement because there is no "this" pointer to pass as a variable. I use ReSharper and it always recommends turning methods into static whenever they don't refer to a class variable.

like image 20
Otávio Décio Avatar answered Sep 23 '22 06:09

Otávio Décio