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
LVL 1
ValimaiAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.