Array class inheritance

All arrays that I create in C # inherit implicitly from the Array class. So, why methods like Sort (), etc., are not available for the array I create. For example, consider the following code:

int [] arr = new int[]{1,2,3,4,5}; Console.WriteLine(arr.Length); //This works,Length property inherited from Array Array.Sort(arr); //Works arr.Sort(); //Incorrect ! 

Please help Thanks.

+4
source share
4 answers

This is because the Sort method is a static method defined in the Array class, so you need to call it like this:

 Array.Sort(yourArray); 

You do not need an instance of the class to call the static method. You call it directly from the class name. In OOP, there is no concept of inheritance for static methods.

+12
source

Sort is a static method of the Array class, so you call it with Array.Sort() . When you try to execute arr.Sort() , you are trying to access an instance method that does not exist.

+2
source

Perhaps you can use the extension method to add a sort function as a member of an instance of type Array.

 public static class ArrayExtension { public static void Sort(this Array array) { Array.Sort(array); } } 

Example

 int [] arr = new int[]{1,2,3,4,5}; arr.Sort(); 

DISCLAIMER: I have not compiled or tried this, but I am sure that it will work.

+2
source

Array.Sort () is a static method, so you won’t see that it hangs on instances. However, you can use the OrderBy () extension method for any IEnumerable to do what you are looking for.

+1
source

All Articles