33

I want to write an extension method for the List class that takes an object and adds it to the front instead of the back. Extension methods really confuse me. Can someone help me out with this?

myList.AddToFront(T object);
Rick Sladkey
  • 33,988
  • 6
  • 71
  • 95
EpiX
  • 1,281
  • 2
  • 16
  • 22

2 Answers2

108

List<T> already has an Insert method that accepts the index you wish to insert the object. In this case, it is 0. Do you really intend to reinvent that wheel?

If you did, you'd do it like this

public static class MyExtensions 
{
    public static void AddToFront<T>(this List<T> list, T item)
    {
         // omits validation, etc.
         list.Insert(0, item);
    }
}

// elsewhere

List<int> list = new List<int>();
list.Add(2);
list.AddToFront(1);
// list is now 1, 2

But again, you're not gaining anything you do not already have.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
1

Instead of using List, you can use IList interface which provides the extension methods for many more collections like BindingList or more. Here are my extension methods for list

Syntax:

public static class ExtensionMethods
{
    public static void AddToFront<T>(this IList<T> list, T item)
    {
         if(list is null) throw new ArgumentNullException("Can't add items to null List");
         list.Insert(0, item);
    }

    public static bool IsNullOrEmpty<T>(this IList<T> list)
    {
         if(list is null || list.Count == 0) return true;
         return false;
    }
}
Tarique Naseem
  • 1,617
  • 2
  • 15
  • 17
ralofpatel
  • 49
  • 3