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?
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?
Very good debate on that subject here (SO). I am in the camp of if-it-can-be-made-static-make-it-static. I believe this because of the notion of why one would have an instance method that does not use any instance data. Is it truly an instance method in that case or is it actually a class method?
The static is instantiated at first use and will stay in memory. If it won't be used anymore, it may be an issue. Static are harder to test (moke etc ...).
For me, the greatest benefit of this ReSharper advice (you can set it as a warning, suggestion, or hint). Is that it encourages me to make as many methods static as possible. This is a Good Thing, since a static method has no direct dependency on the class it is a member of. This means that it can easily be moved to another class as a static member.
Another neat trick with statics in ReSharper is to make a set of related methods static by using the "Make Method Static" refactoring. This will move some of the dependencies into method parameters. When you look at this set of methods later, you may find they all access a particular object of a particular type. You can then use the "Make method non-static" refactoring, and specify that object as being the new this pointer. That moves your method into the other class.
From this:
to this:
to this:
I find that comment very useful as it points out two important things:
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?
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.
It's not a complaint, it's just advice.
You don't have to push "this" onto the function's stack for a static method. That's another reason it's cheaper.