none
Method / Casting Problem RRS feed

  • Question

  • I wish to write a sorting algorithm that will work for any List of comparable items.  I figure the method definition should look something like this:

    Code Snippet

    static void Sort(IList<IComparable> list)
    {
      // Method implementation
    }



    That works as expect except that I must do an ugly cast every time I call the method:

    Code Snippet

    List<string> someStrings = new List<string>();
    // add some items
    Sort((IList<IComparable>)someStrings);



    I want a way to just do this:

    Code Snippet

    Sort(someStrings);



    My problem really as more to do with casting than anything else.  Is there a way I can tell the compiler that I want objects matching the IList<IComparable> type to be automatically cast?

    Hope it is clear what I am asking.  Any help would be greatly appreciated.
    Monday, March 31, 2008 6:30 PM

Answers

  • > That works as expect except that I must do an ugly cast every time I call the method:

     

    That code will not work; at run time it fails as follows:

     

    Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' to type 'System.Collections.Generic.IList`1[System.IComparable]'.

     

    You see, IList<IComparable> is not an interface implemented by List<string> so the cast fails.  (This is a common misunderstanding of how generics work.)

     

    However, the following signature should do exactly what you want:

     

    Code Snippet

    static void Sort<T>(IList<T> list) where T : IComparable

    {

    // Method implementation

    }

     

     

     

    Tuesday, April 1, 2008 1:36 AM

All replies

  • > That works as expect except that I must do an ugly cast every time I call the method:

     

    That code will not work; at run time it fails as follows:

     

    Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' to type 'System.Collections.Generic.IList`1[System.IComparable]'.

     

    You see, IList<IComparable> is not an interface implemented by List<string> so the cast fails.  (This is a common misunderstanding of how generics work.)

     

    However, the following signature should do exactly what you want:

     

    Code Snippet

    static void Sort<T>(IList<T> list) where T : IComparable

    {

    // Method implementation

    }

     

     

     

    Tuesday, April 1, 2008 1:36 AM
  • Thank you very much. 

    I have been coding in C# for many years and was somehow unfamiliar with the 'where' keyword.  Makes me wonder what else I have missed.

    Thanks again.
    Tuesday, April 1, 2008 12:10 PM