Alex Rivera | Logout

Should C# methods that *can* be static be static?

Asked 2009-04-08T20:49:05.163
114

Should C# methods that can be static be static?

We were discussing this today and I'm kind of on the fence. Imagine you have a long method that you refactor a few lines out of. The new method probably takes a few local variables from the parent method and returns a value. This means it could be static.

The question is: should it be static? It's not static by design or choice, simply by its nature in that it doesn't reference any instance values.

Edit
Report

5 Answers

4

Making something static just because you can is not a good idea. Static methods should be static due to their design, not due to happenstance.

Like Michael said, changing this later will break code that's using it.

With that said, it sounds like you are creating a private utility function for the class that is, in fact, static by design.

answered 2009-04-08T20:58:12.397
2

It depends but generally I do not make those methods static. Code is always changing and perhaps someday I will want to make that function virtual and override it in a subclass. Or perhaps some day it will need to reference instance variables. It will be harder to make those changes if every call site has to be changed.

answered 2009-04-08T20:51:42.210
2

Personally I would have no choice but to make it static. Resharper issues a warning in this case and our PM has a rule "No warnings from the Resharper".

answered 2009-04-08T21:12:40.553
1

I suggest that the best way to think about it is this: If you need a class method that needs to be called when no instances of the class are instantioated, or maintains some kind of global state, then static is a good idea. But in general, I suggest you should prefer making members non-static.

answered 2009-04-08T20:58:01.540
1

I would definitely turn anything I can into static for a different reason:

Static functions, when JIT'd, are called without a "this" parameter. That means, for example, that a 3 parameter non-static function (member method) gets pushed with 4 params on the stack.

The same function compiled as a static function would get called with 3 parameters. This can free up registers for the JIT and conserve stack space...

answered 2009-04-16T08:39:15.293

Your Answer