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);
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.
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.
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.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With