Reputation: 4104
To my understanding, the only purpose of static is to enable a method to be called on the class itself, not an instance of it. But if the method is also private, you'll only be able to call it from within the class. So, is there a reason to declare something as both private and static? ReSharper recommends I make many of my methods static and I just don't see the point for the private ones.
Upvotes: 1
Views: 121
Reputation: 56984
Performance. It is a (micro) optimization. The CLR needs to perform less steps to find the method that he needs to execute.
For a detailed explanation: http://msdn.microsoft.com/en-us/library/79b3xss3.aspx
A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.
Upvotes: 1
Reputation: 73502
If your private method doesn't uses any instance methods or fields or properties then it is good to mark it as static.
Doing so, you get call
opcode emitted in IL which will not perform any "null checking" before calling the method. where as instance methods emits callvirt
opcode which does that "null checking" before calling the method. This helps you to get performance benefits.
Upvotes: 1
Reputation: 460340
Yes, if you have a (public
or whatever) static
method in the class and this method needs to use your private
method. That doesn't work if it's not static
.
public static void Foo1()
{
Foo2(); // compile time error
}
private void Foo2()
{
}
Methods need to be instance methods only if they need to use fields or properties that are not static (among other reasons like inheritance). Therefore it's best practice to make it static.
Upvotes: 2
Reputation: 62542
You tend to see this if a method has been written that doesn't use the state of the object and is an implementation detail. You could just make it private
, but some people prefer to make it static
as well to fully indicate that the method doesn't touch the state.
Personally I'd just go with the private
.
Upvotes: 0