|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
Introduction and BackgroundSince the .NET Framework 3.0, the developer has an interesting tool to enable him to add methods to already existing types without deriving or recompiling it. For example, the LINQ standard operators that add query functionality to the interfaces Extension Methods are static methods that can be invoked by using the instance method syntax. They make it possible to extend existing types with additional methods. This article shows how this concept can be used to sort index-based generic lists. Sorting Generic Index-based ListsWhen you browse the instance methods of the types ArrayList list = new ArrayList() {3 , 5 , 8 , 6 , 7 , 6 , 2 , 1 , 9};
list.Sort();
Observing the other index-based collections, however, you will miss a sorting method. Since every index-based collection implements IList<int> list = new int[10] {3 , 5 , 8 , 6 , 7 , 6 , 2 , 1 , 9};
list.Sort(); //Compiler error, for IList<T> doesn't possess a method Sort()
So, you would either have to convert your collection to one of the appropriate collection types above, or implement your own sorting algorithm. And, here comes the concept of Extension Methods into play. Instead of simply implementing a method that takes an Extension Methods are implemented in a Example CodeIn this example, I implemented the Bubble Sort algorithm: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Extensions
{
public static class SortingExtensionProvider
{
public static void Sort<T>(this IList<T> list) where T : IComparable
{
//This extension method is visible where the namespace
//Extensions is brought into scope
Sort(list, 0, list.Count - 1);
}
public static void Sort<T>(this IList<T> list,
int startIndex, int endIndex) where T : IComparable
{
//This extension method is visible where the namespace
//Extensions is brought into scope
//Bubble Sort
for (int i = startIndex; i < endIndex; i++)
for (int j = endIndex; j > i; j--)
if (list[j].IsLesserThan(list[j - 1]))
list.Exchange(j, j - 1);
}
private static void Exchange<T>(this IList<T> list, int index1, int index2)
{
//This extension methods is only visible within SortingExtensionsProvider
T tmp = list[index1];
list[index1] = list[index2];
list[index2] = tmp;
}
private static bool IsLesserThan(this IComparable value, IComparable item)
{
//This extension method is only visible within SortingExtensionsProvider
return value.CompareTo(item) < 0;
}
}
}
Be aware that the Now, if you bring the namespace using Extensions;
...
IList<int> list = new int[10] {3 , 5 , 8 , 6 , 7 , 6 , 2 , 1 , 9};
list.Sort(); //Extension method
History
|
||||||||||||||||||||||