Why are Array.Sort() and Array.IndexOf() methods static?
Asked Answered
D

2

6

Always was interested why are Array.Sort() and Array.IndexOf() methods made static and similar ArrayList.Sort() and ArrayList.IndexOf() are designed as member methods. Thank you for any ideas.

Descent answered 7/10, 2008 at 4:48 Comment(1)
Good response of Hans Passant hereJerejereld
R
5

In my view Array class is basically a class representation of the fixed size arrays that we declare using [] in program (you can draw the analogy like int has it's class (structure) representation as System.Int32).

Also Array class does not contain the actually array data in any instance variables but it provides just static utility functions which can be utilized to do sorting and searching in the declared fixed size arrays.

On the other hand, ArrayList is a collection class, which provides dynamic size array implementation and it has it's own data-structure to contain the data. Therefore the said methods are instance methods, so that they can work on the that particular instance's data.

Ripuarian answered 7/10, 2008 at 5:3 Comment(0)
M
3

A collection class like ArrayList encapsules some kind of internal storage (presumably an array which is resized as needed, but it could also be a linked list or some other implementation). Metods like IndexOf and Sort needs access to the underlying private storage to be efficient, so they have to be instace methods.

An Array on the other hand is not encapsulated, there is public access directly to the storage. The Array.IndexOf and Array.Sort methods does not need any special access to the array data, so they might as well be static metods.

Maitland answered 5/1, 2009 at 18:47 Comment(1)
They might as well be member methods, though, right? int might as well be renamed to integer because it's more readable to non-programmers, though, right?Rackrent

© 2022 - 2024 — McMap. All rights reserved.