Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify parameter for generic list type extension method in c#

I am trying to make an extension method that will shuffle the contents of a generic list collection regardless of its type however im not sure what to put in between the <..> as the parameter. do i put object? or Type? I would like to be able to use this on any List collection i have.

Thanks!

public static void Shuffle(this List<???????> source)
{
    Random rnd = new Random();

    for (int i = 0; i < source.Count; i++)
    {
        int index = rnd.Next(0, source.Count);
        object o = source[0];

        source.RemoveAt(0);
        source.Insert(index, o);
    }
}
like image 576
Grant Avatar asked Aug 15 '09 01:08

Grant


People also ask

Can you achieve method extension using interface?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

How to declare extension method in C#?

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. The IntExtensions class will contain all the extension methods applicable to int data type.

How do you declare an extension method?

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. string s = "Hello Extension Methods"; int i = s. WordCount(); You invoke the extension method in your code with instance method syntax.

Which keyword is used to apply constraints on type parameter?

In this article. The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.


1 Answers

You need to make it a generic method:

public static void Shuffle<T>(this List<T> source)
{
    Random rnd = new Random();

    for (int i = 0; i < source.Count; i++)
    {
        int index = rnd.Next(0, source.Count);
        T o = source[0];

        source.RemoveAt(0);
        source.Insert(index, o);
    }
}

That will allow it to work with any List<T>.

like image 146
Reed Copsey Avatar answered Oct 19 '22 23:10

Reed Copsey