Question Details

No question body available.

Tags

c# code-quality maintainability static-methods

Answers (1)

Accepted Answer Available
Accepted Answer
July 16, 2025 Score: 15 Rep: 139,666 Quality: Expert Completeness: 60%

Garbage collection deals with objects, or, in other words, instances of specific types. GC doesn't care nor deal with methods, unless you store a method as an object (such as an instance of Func).

Similarly, CA-1822 has nothing to do about memory consumption, but about an extra check that is done at runtime for non-static methods. When a method is static, it can be called directly—it will always exist. An instance method, however, being bound to an instance, requires this instance to exist. Which means that the runtime should first start by checking the existence of this instance. Making methods static is about avoiding this extra check.

Putting aside that this is absolutely negligible for the scenario above

Sort of. This is one of the drawbacks of some CA rules—focusing your attention on nanosecond optimizations, as if this actually matters for the average business code.

Note, however, that unlike CA1860 that invites you to use Count > 0 on collections, instead of Any() just to avoid an extra call, at a cost of code becoming less clear, CA-1822 is actually a good thing in terms of code explicitness. After all, if a given method doesn't use any instance methods (and is not part of an interface or a base class), then mark it static—not as a part of a nanosecond optimization, but to make it clear.

Hypothetically, assuming I get a similar warning for field members (not methods) (say it makes sense) - if I start marking fields as static - in this case - my assumption above holds - in that more memory will be held over time without being released ?

It depends.

Imagine a class A with an instance field x, and two objects, a1 and a2, being initialized, and then left for GC.

After initialization, you'll end up with x using twice the memory: once per instance. At some moment, GC will release this memory.

Imagine, now, that x is static.

After initialization, you'll have half the memory used compared to the previous case.

But it will not be released.

Is this a good or a bad thing? It depends. There are cases where you absolutely want GC to free everything. And then there are cases where it is much more interesting to use memory once, and not multiplied by the number of instances of the object.

Here again, don't overthink it in terms of performance or memory consumption. If the field makes sense as instance field, make it instance field. If it is shared by all instances, make it static.