D
David Veeneman
Does a SortedList have a more limited ability to cast that an ArrayList?
I have an array of objects that I store in an ArrayList. I use an ArrayList
because of its flexibility in adding and removing items. I use the array to
populate a list box, so I use the ArrayList CopyTo() method to get a typed
array, which I pass to the list box. That works fine.
Here's my problem: I'd like to do the same thing using a SortedList, so that
I can pull items from the list by ID (key). But when I do, I get an
InvalidCastException from the CopyTo() method, even though an ArrayList can
perform the cast.
Am I missing something here? I'd like to be able to use the SortedList. Is
there a way to get the cast to work?
Below is a complete console app that shows the issue. Thanks for your help.
--
Dave Veeneman
Foresight Systems
Chigago
using System;
using System.Collections;
namespace ConsoleApplication1
{
public class MyClass
{
public int ID;
public string Name;
public MyClass(int theID, string theName)
{
ID = theID;
Name = theName;
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
// Declarations
MyClass c;
// Add 5 instances of MyClass to a SortedList
SortedList list = new SortedList();
for (int i = 0; i < 5; i++)
{
c = new MyClass(i, "tempname");
list.Add(c.ID, c);
}
// Copy the sorted list to a MyClass array
MyClass[] typedList = new MyClass[list.Count];
list.CopyTo(typedList, 0);
}
}
}
I have an array of objects that I store in an ArrayList. I use an ArrayList
because of its flexibility in adding and removing items. I use the array to
populate a list box, so I use the ArrayList CopyTo() method to get a typed
array, which I pass to the list box. That works fine.
Here's my problem: I'd like to do the same thing using a SortedList, so that
I can pull items from the list by ID (key). But when I do, I get an
InvalidCastException from the CopyTo() method, even though an ArrayList can
perform the cast.
Am I missing something here? I'd like to be able to use the SortedList. Is
there a way to get the cast to work?
Below is a complete console app that shows the issue. Thanks for your help.
--
Dave Veeneman
Foresight Systems
Chigago
using System;
using System.Collections;
namespace ConsoleApplication1
{
public class MyClass
{
public int ID;
public string Name;
public MyClass(int theID, string theName)
{
ID = theID;
Name = theName;
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
// Declarations
MyClass c;
// Add 5 instances of MyClass to a SortedList
SortedList list = new SortedList();
for (int i = 0; i < 5; i++)
{
c = new MyClass(i, "tempname");
list.Add(c.ID, c);
}
// Copy the sorted list to a MyClass array
MyClass[] typedList = new MyClass[list.Count];
list.CopyTo(typedList, 0);
}
}
}