Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method for List<T> AddToFront(T object) how to?

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);
like image 490
Ryan Lee Avatar asked Jul 09 '11 02:07

Ryan Lee


People also ask

How do you find the extension method?

An extension method must be defined in a top-level static class. An extension method with the same name and signature as an instance method will not be called. Extension methods cannot be used to override existing methods. The concept of extension methods cannot be applied to fields, properties or events.

What are extension methods explain with an example?

In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.

Can we define extension method for a class?

An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.

What is extension method in C++?

An extension method allows you to add functionality to an existing type without modifying the original type or creating a derived type (and without needing to recompile the code containing the type that is extended.)


1 Answers

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.

like image 168
Anthony Pegram Avatar answered Sep 21 '22 15:09

Anthony Pegram