[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 554
  • Last Modified:

How to use generic type T with delegate?

hi there,

I am in the middle of refactoring my class to be a generic class.  I am having problems with converting the CompareTo part of the code.

Fact: T has a Int32 property called MyIndex

Here is the Half converted code. CompareTo is giving me grief :)
<snip>
    List<T> myList = new List<T>();
    myList.Sort(delegate(T a, T b)
    {
        return a.MyIndex.CompareTo(b.MyIndex);
    });
</snip>

return a.MyIndex.CompareTo(b.MyIndex); // <--- Help with this part of the conversion pls.

I have tried something like but doesn't work.
return a.GetType().GetProperty("MyIndex").CompareTo(b.GetType().GetProperty("MyIndex"));

thanks
0
Valimai
Asked:
Valimai
1 Solution
 
Jaime OlivaresSoftware ArchitectCommented:
You can do this. Your class can be generic, but the type allowed could be derived from some class or interface, so you can cast to the parent class or interface because trying to use MyIndex, something like:

return ((IMyInterface)a).MyIndex.CompareTo((IMyInterface)b).MyIndex);

this is, assuming a and b are types implementing the IMyInterface interface

0
 
ValimaiAuthor Commented:
That is a great idea. As MyIndex is a required field. Let me try this and see how i go :)
0
 
Expert1701Commented:
Another option is to require that your generic type, T, actually implements the interface:

  interface ITestInterface
  {
    int MyIndex { get; }
  }

  class TestClass<T> where T : ITestInterface
  {
    List<T> myList = new List<T>();

    public void TestMethod()
    {
      myList.Sort(delegate(T a, T b)
      {
        return a.MyIndex.CompareTo(b.MyIndex);
      });
    }
  }
0

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now