I guess this is more of a framework design question. I recently wondered why most of the methods in System.Array are static. My gut reaction always is to use e.g. IndexOf(object) on the Array instance, not as System.Array.IndexOf(array, object). Is there a main principle behind the decision, whether to make a method static or not?
I found this question: When is it best to use Static Functions in ASP.NET
But it didn't satisfy me :-/
The most time you inherit of
System.Array
is using a single dimension array. like:When you define
int[]
this implicitly derived fromSystem.Array
type like @Sergey Rybalkin says. In this case the methodIndexOf
would surely be best implemented as a instance method and not as static method.But there is another types that inherit from System.Array like mult dimension arrays. In this case (mult dimension) the method
IndexOf
does not make sense.Test this:
The last like throws a RankException with the message
"Only single dimension arrays are supported here."
Perhaps, and most probably, because of that this method is implemented as static.
...
About the comment
Is there a main principle behind the decision, whether to make a method static or not?
There is, and the principle is quite simple. The instance method represents a action or behavior of a object. The static method is a function of the system that is logic related with the class, or in some cases a method you want to call without creating an instance of the class.
Think in
System.Math
class how mess will be if you need instance math every time you want call a method likeSqrt
orPow
?The final example I will give to you is the
System.Text.RegularExpressions.Regex
class. This class have aMatch
method implemented as instance and an overload implemented as static.Each one is used in a diferent context. The instance is used when you use the same pattern multiple times. The static when you use the pattern a unique time in your code.