I have a list that contains FrameworkElements and I want to create an extension method called MoveToTop. All this will do is accept an item that is part of that list and move it to the beginning of the list. I know this could be accomplished without the use of an extension method, but I would like it to be implemented as an extension method.
I am having trouble trying to figure out the syntax for creating an extension method that accepts a generic parameter. I know this isn't correct, but if someone could give me an idea how how to accomplish this, I would appreciate it.
public static class Extensions { public static void MoveToTop(this ICollection<T> sequence) { //logic for moving the item goes here. } }
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.
Extension Methods is a new feature in C# 3.0 and the Common Language Runtime, which allows existing classes to use extra methods (extension methods) without being implemented in the same class or obtained by inheritance.
Generics are a way to tailor a class or method to a specific type. A generic method or class is designed to work for any type. This is most easily illustrated in the List<T> class, where it can be tailored to be a list of any type. This gives you the type-safety of knowing the list only contains that specific type.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
You were close, just need the <T>
after the method name before the parenthesis. That's where the generic type parameter list for generic methods is placed. It declares the generic type parameters the method will accept, which then makes them available to be used in the arguments, return values, and method body.
public static class Extensions { public static void MoveToTop<T>(this ICollection<T> sequence) { //logic for moving the item goes here. } }
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