I'm trying to understand static methods and I've reached a confusing point.
Focusing only on methods for this question, if I create an instance of my object (where the class itself is not static) then I typically only have access to the public, protected and or internal methods (depending on scope/encapsulation). In other word, I don't have access to private methods.
I've read that, although minimal, static methods are slightly more efficient than non-static methods.
So, when creating a private method with a return type of void, and excluding when you're creating a reference of an object from within itself, why would you ever not make it static? All the code I've ever seen doesn't do this, so I can only assume I've missed the point.
Static methods cannot access the non-static member data in the class.
Static methods are typically supposed to be stateless and therefore have no access to the instance state. In contrast, instance methods are stateful and can therefore read and modify the instance's state.
Typical examples of stateless methods are:
Of course, static methods aren't always stateless though, there are samples of static stateful methods. There is one single state for the class then:
These implementations need slightly more care though, since the class's state is also shared by all threads within the process.
I've read that, although minimal, static methods are slightly more efficient than non-static methods.
That's not unconditionally true: only the methods that could otherwise be static
but are not made static
by omission would be more efficient. Otherwise, you would need to pass a reference to the object manually, leveling up the playing field. Moreover, CLR is optimized so much that the difference is hard to measure.
To answer your question, there is no reason to make a method non-static if it does not access instance state through properties or variables. However, all methods that access per-instance state should be non-static for readability, because there is no performance to gain from making them static and passing the instance manually.
To illustrate the point, you should do this
private void AddCount(int number) {
current += number;
}
rather than this:
// Do not do this!
private static void AddCount(MyClass obj, int number) {
obj.current += value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With