Jack Valmadre

Hi
I have an array of integers, where each one is an index for an array of objects, and I'm trying to sort the array by the .name property of the objects. I've set up a class using the IComparer interface to do this.

    List<int> SubjList = new List<int>();
SubjectIndexComparer<int> subjectIndexComparer = new SubjectIndexComparer<int>();
...
SubjList.Sort(subjectIndexComparer);

  public class SubjectIndexComparer<T> : IComparer<T>
{
...
public int Compare(T x, T y)
{
string textX = Singleton.Instance.subjList[(int)x].name;
string textY = Singleton.Instance.subjList[(int)y].name;
...
}
}

However, this doesn't work because I can't cast x and y from type T to int. I only want the function to work if T can be casted to an integer. How can I implement this I don't actually need the function to be generic, it would be fine if it just took integers, but the List.Sort() method required that form. Thanks in advance.


Re: Visual C# Language Casting generic parameters to int

timvw

Code Snippet

class SubjectIndexComparer : IComparer<int>
{
public int Compare(int x, int y)
{
string valueX = Singleton.Instance.subjList[x].name;
string valueY = Singleton.Instance.subjList[y].name;
return valueX.CompareTo(valueY);
}
}