dlamblin dlamblin - 23 days ago 6
C# Question

Method can be made static, but should it?

Resharper likes to point out multiple functions per asp.net page that could be made static. Does it help me if I do make them static? Should I make them static and move them to a utility class?

Answer

Static methods versus Instance methods
10.2.5 Static and instance members of the C# Language Specification explains the difference. Generally, static methods can provide a very small performance enhancement (not to mention a memory saving depending on the number of instances your class might expect to create) over instance methods, but only in somewhat extreme situations.

Rule CA1822 in FxCop or Code Analysis states:

"After [marking members as static], the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that ensures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."

Utility Class
You shouldn't move them to a utility class unless it makes sense in your design. If the static method relates to a particular type, like a ToRadians(double degrees) method relates to a class representing angles, it makes sense for that method to exist as a static member of that type (note, this is a convoluted example for the purposes of demonstration).