mszabolcs
mszabolcs

Reputation: 67

C# - T type, array, list indexing

I want to write a method where i can send any type of [], List<>...etc. But in the code when I use T and I want to index the input array, list or anything the error says "Cannot apply indexing with [] to an expression of type 'T'". Theres any solution for this or I have to write a separate code for array, list..etc?

public void NormSort<T>(ref T input, int n)
{
    for (int i = 0; i < n - 2; i++)
    {
        for (int j = 0; j < n - 1; j++)
        {
            if (Comparer<T>.Default.Compare(input[i], input[j]) > 0)
            {
                Swap<T>(input[i], input[j]);
            }
        }
    }
}

public void Swap<T>(T item1, T item2)
 {
     var temp = item1;
     item1 = item2;
     item2 = temp;
 }

So wheres the input[i], input[j], there i got that error.

Upvotes: 2

Views: 96

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062855

The easiest way to do that is probably to make the parameter IList<T> for some T, since IList<T> has the indexer support and both arrays and lists implement IList<T>. Note that you probably don't need to pass the n here, since IList<T> also has a .Count property. So:

public void NormSort<T>(IList<T> input) {
    int n = input.Count;
    // ...
}

Note that your Swap method won't work, however; that isn't pass-by-ref, and even if it was: you can't pass indexer values by ref - you need to get and set separately; perhaps:

public static void NormSort<T>(IList<T> input)
{
    int n = input.Count;
    var comparer = Comparer<T>.Default;
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = i; j < n; j++)
        {
            T x = input[i], y = input[j];
            if (comparer.Compare(x, y) > 0)
            {
                input[i] = y;
                input[j] = x;
            }
        }
    }
}

Note that a more typical implementation here would be an extension method:

public static void Sort<T>(this IList<T> input) {...}

Then you can just use:

myListOrArray.Sort();

and as a nice side-effect, if the compiler knows it is a List<T>, it will prefer the inbuilt List<T>.Sort() which will be more efficient - but it will compile for any IList<T> type.

Upvotes: 4

Stefano Liboni
Stefano Liboni

Reputation: 149

Use IEnumerable and you can have all type of collections:

public void NormSort<T>(ref IEnumerable<T> input, int n)
{ ...
}

Upvotes: -2

Related Questions