Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReSharper complains when method can be static, but isn't

Why does ReSharper complain when a method can become static, but is not?

Is it because only one instance of a static method is created (on the type) and thus save on performance?

like image 931
Andreas Grech Avatar asked Apr 26 '09 05:04

Andreas Grech


People also ask

Should I make methods static if possible?

My short answer: Yes, you can convert them to static methods as ReSharper suggests. There is no harm in doing so. Rather, by making the method static, you are actually guarding the method so that you do not unnecessarily slip any instance members into that method.

Why static method should be avoided?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous.

What happens if we make a method static?

"static" , which declares the method as one that belongs to the entire class and not a part of any objects of the class. The main must always be declared as static since the interpreter uses this method before any objects are created. if a method's functionality is for class/program level then we declare it as static.

When Can a method be static C#?

A static method in C# is a method that keeps only one copy of the method at the Type level, not the object level. That means, all instances of the class share the same copy of the method and its data. The last updated value of the method is shared among all objects of that Type.


Video Answer


1 Answers

I find that comment very useful as it points out two important things:

  1. It makes me ask myself if the method in question should actually be part of the type or not. Since it doesn't use any instance data, you should at least consider if it could be moved to its own type. Is it an integral part of the type, or is it really a general purpose utility method?

  2. If it does make sense to keep the method on the specific type, there's a potential performance gain as the compiler will emit different code for a static method.

like image 125
Brian Rasmussen Avatar answered Sep 25 '22 12:09

Brian Rasmussen