4

This is a purely hypothetical question.

Say I create a class method that contains no references to instance variables or other resources. For example (C#):

protected string FormatColumn(string value, int width)
{
    return value.Trim().PadLeft(width);
}

As far as I can see, there is absolutely no reason why this method could not be declared static:

  • It only uses method-scope variables.
  • It doesn't override a base class method.
  • It's not virtual or abstract.

My questions are:
Is there any benefit to calling a static method over an instance method?
If so, why doesn't the compiler implicitly convert this to a static method?

I'm certain I've missed some key point here. Any ideas?

4 Answers 4

11

You should read this article about Code Analysis rule #CA1822, which states:

Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.

2
  • What I gather from that is future-proofing your code library. While static members are benficial, if you change it to an instance method in a later version, you may break other code dependant on it. Is that correct? Aug 17, 2012 at 4:05
  • 1
    @Hand-E-Food: when you have to change it to an instance member, there must be reason for it, meaning the function now will depend on the internal state of the instance - which means there must be some change in semantics. That may break code dependant on it just because of the changed semantics - but that will be also the case when the function was not static before.
    – Doc Brown
    Aug 17, 2012 at 6:50
0

Static methods are usually utility operations shared among instances of a specific class, a.k.a utility methods. For example the String.Join() method which takes an array and join the elements by using a separator character or string.

So, my rule is that if the method is a utility shared functionality specific to instances of that class then it can be static.

It would be weird to have to create a new string in order to use the Join() method to join multiple strings into a new one.

-1

This is an opinion rather than sure solid facts, I present it here as it may be of help. here it goes:

One main concern with statics is thread safety. Static fields within the static classes (rather than static methods themselves) may cause the unexpected results when multiple threads are in action.

Is there any benefit to calling a static method over an instance method?

Yes, assuming the method uses an instance variable of some sort such as a counter for example, If you do this you are sure that the variables used within the instance method will be allocated separately for each object. You may choose to lock your object and the results would be guaranteed to be correct when multiple threads access it.

why doesn't the compiler implicitly convert this to a static method?

I really don't know for sure what the compiler does, but if it does not turn such methods to static methods, one reason for that may be because of thread safety. This is because, the compiler will have to tweak the code with locks to make it return the correct result. Locks slows down the execution in mulch-threaded processing.

Edit: Fixed a type as suggested by @WinstonEwert's comment.

9
  • 2
    I'm not clear why you've brought up static fields since there aren't any fields in the question. Aug 17, 2012 at 3:41
  • @JohnSaunders, thanks for letting me know about your concern. C# allows you to define a fields and properties in classes. I am not clear why do you say it does not. See for example: msdn.microsoft.com/en-us/library/aa645751(v=vs.71).aspx
    – NoChance
    Aug 17, 2012 at 11:54
  • @WinstonEwert, thanks for your comment. I brought up static fields because the compiler (or a person) can't convert a non-static method to a static method without careful examination of the static property of its fields whether those are explicitly defined or implicitly defined by other methods such as Trim. That is why in the documentation of classes, MS specifies clearly when a function is thread safe or not.
    – NoChance
    Aug 17, 2012 at 11:59
  • You seem to be conflating methods and classes. Classes have fields, methods do not. Aug 17, 2012 at 12:18
  • @WinstonEwert, now I see your point, this was a typo. I am clear about the difference....Thanks.
    – NoChance
    Aug 17, 2012 at 12:22
-2

Since your method is not final (sealed)nor private, it means that it could be overridden by a child class, which is at least one reason why the compiler can't transform that method into a static method.

Now, if you make it either private or final (sealed), then there's no reason not to make it static, but then the performance improvement would be minimal, since it's only passing one less parameter (no need for virtual call if method is private and/or final) Also, as Bernard said, that would also remove the null check on the instance, which could still occur even with a private or a protected method.

For example with this code :

public static staticMethod() {
    MyClass class= ...
    class.FormatColumn("a", 1) // this should throw an exception if column is null, but not when FormatColumn becomes static
}

for a private method, I guess the compiler could check all calls from a static method and add necessary null pointer checks, since it has access to the whole class, but then we would probably lose in jumps what we saved by adding an additional pointer to this.

2
  • 1
    Question is tagged c#; in C#, methods have to be declared virtual if they are to be virtual.
    – AakashM
    Aug 17, 2012 at 8:06
  • 1
    -1: C# is not Java Aug 17, 2012 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.