Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create extension method on generic collection

Tags:

c#

.net

oop

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.     } } 
like image 647
Justin Avatar asked Feb 21 '12 15:02

Justin


People also ask

How do you declare an 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.

How can use generic extension method in C#?

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.

What is generic extension?

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.

What is used of extension methods and how do you create and use it?

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.


1 Answers

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.     } } 
like image 84
James Michael Hare Avatar answered Sep 21 '22 17:09

James Michael Hare