0
0
CsharpHow-ToBeginner · 3 min read

How to Use Array.Sort in C# for Sorting Arrays

Use Array.Sort in C# to sort the elements of an array in ascending order. You can call Array.Sort(yourArray) to sort the array in place, or use overloads to customize sorting with a comparer.
📐

Syntax

The basic syntax to sort an array is Array.Sort(array). This sorts the array elements in ascending order. You can also use overloads like Array.Sort(array, comparer) to define custom sorting rules.

  • array: The array you want to sort.
  • comparer (optional): An object that defines how to compare elements.
csharp
Array.Sort(array);

// Or with a custom comparer
Array.Sort(array, comparer);
💻

Example

This example shows how to sort an integer array using Array.Sort. The array is sorted in ascending order and printed before and after sorting.

csharp
using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 5, 3, 8, 1, 4 };

        Console.WriteLine("Before sorting:");
        foreach (int num in numbers)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();

        Array.Sort(numbers);

        Console.WriteLine("After sorting:");
        foreach (int num in numbers)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}
Output
Before sorting: 5 3 8 1 4 After sorting: 1 3 4 5 8
⚠️

Common Pitfalls

One common mistake is expecting Array.Sort to return a new sorted array. It sorts the original array in place and returns void. Another pitfall is not using a custom comparer when sorting complex types or when a different order is needed.

Also, sorting null arrays or arrays with null elements can cause exceptions.

csharp
int[] numbers = { 3, 1, 2 };

// Wrong: expecting a new sorted array
// int[] sorted = Array.Sort(numbers); // This causes a compile error

// Right: sort in place
Array.Sort(numbers);
📊

Quick Reference

MethodDescription
Array.Sort(array)Sorts the array in ascending order in place.
Array.Sort(array, comparer)Sorts the array using a custom comparer.
Array.Sort(array, index, length)Sorts a range within the array.
Array.Sort(array, index, length, comparer)Sorts a range with a custom comparer.

Key Takeaways

Array.Sort sorts the original array in place and does not return a new array.
Use Array.Sort(array) for simple ascending order sorting.
Use overloads with a comparer to customize sorting behavior.
Avoid sorting null arrays or arrays containing null elements without checks.
Remember that Array.Sort modifies the original array directly.