Joe
Joe

Reputation: 303

Inheriting from Array class

All arrays i create in C# inherit implicitly from the Array class. So why are methods like Sort() etc not available to 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 Thank You.

Upvotes: 4

Views: 5574

Answers (4)

Jeffrey
Jeffrey

Reputation: 509

You could probably use an extension method to add a Sort function as an instance member of the Array type.

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 and tried this, but I am pretty sure that it will work.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

It's because the Sort method is a static method defined on the Array class so you need to call it like this:

Array.Sort(yourArray);

You don't need an instance of the class to call a static method. You directly call it on the class name. In OOP there's no notion of inheritance for static methods.

Upvotes: 12

Steve Michelotti
Steve Michelotti

Reputation: 5213

Array.Sort() is a static method so you won't see it hanging off instances. However, you can use the OrderBy() extension method on any IEnumerable to do what you are seeking.

Upvotes: 1

Graham Clark
Graham Clark

Reputation: 12956

Sort is a static method on the Array class, that's why you call it using Array.Sort(). When you try arr.Sort(), you're trying to access an instance method which doesn't exist.

Upvotes: 2

Related Questions