Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are most methods of System.Array static? [closed]

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 :-/

like image 345
needfulthing Avatar asked May 23 '13 12:05

needfulthing


1 Answers

The most time you inherit of System.Array is using a single dimension array. like:

int[] a1 = new int[2];

When you define int[] this implicitly derived from System.Array type like @Sergey Rybalkin says. In this case the method IndexOf 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:

int[,] arr = new int[2, 2];

arr[0, 0] = 3; arr[1, 0] = 4;
arr[0, 1] = 5; arr[1, 1] = 6;

Array.IndexOf(arr, 4);

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 like Sqrtor Pow?

The final example I will give to you is the System.Text.RegularExpressions.Regex class. This class have a Match 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.

like image 156
Jonny Piazzi Avatar answered Sep 18 '22 10:09

Jonny Piazzi