Q: Casting objects from an ArrayList

  • Thread starter Martin Arvidsson, Visual Systems AB
  • Start date
M

Martin Arvidsson, Visual Systems AB

Hi!

I am going crayz, i cant get this to work. and i don't know what the problem
is.

I have this method

public ArrayList ResolveData()
{
ArrayList workingList = new ArrayList();


Loop and stuff
// do stuff

workingList.Add(resolvedString.Split(new char[]{';', '--'});
loop ends here

return workingList
}

Then i have this method

private void MyPrivate()
{
ArrayList myArray = ResolveData();

foreach (ArrayList obj in myArray)
{
string[] resultSet = obj as string[]; <<<< This is where i get the
compile error.
}
}

What am i doing wrong?

Regards
Martin
 
J

Jon Skeet [C# MVP]

I am going crayz, i cant get this to work. and i don't know what the problem
is.

What am i doing wrong?

This line:

foreach (ArrayList obj in myArray)

should just be:

foreach (string[] resultSet in myArray)

The way you've got it at the moment is expecting the ArrayList to be
full of other ArrayLists. There's no way of casting an ArrayList to a
string[], which is why you're getting a compile-time error.

Jon
 
D

DeveloperX

Hi!

I am going crayz, i cant get this to work. and i don't know what the problem
is.

I have this method

public ArrayList ResolveData()
{
ArrayList workingList = new ArrayList();

Loop and stuff
// do stuff

workingList.Add(resolvedString.Split(new char[]{';', '--'});
loop ends here

return workingList

}

Then i have this method

private void MyPrivate()
{
ArrayList myArray = ResolveData();

foreach (ArrayList obj in myArray)
{
string[] resultSet = obj as string[]; <<<< This is where i get the
compile error.
}

}

What am i doing wrong?

Regards
Martin

Well you've got ArrayList in your foreach instead of string[]. Try
this:

System.Collections.ArrayList a = new System.Collections.ArrayList();
a.Add("this is a test".Split(' '));
a.Add("this is a test".Split(' '));
string[] s = (string[])a[0]; // <-- example normal cast
foreach(string[] ss in a) // <--- string array
{
Console.WriteLine(ss.Length);
}
 
M

Marc Gravell

Jon and DeveloperX have hopefully answered your original question; as
an additional - if you can, I strongly suggest moving to .Net 2.0 and
using generics, such as List<T>; because this is strongly typed, it
makes it absolutely clear what the problem is *at compile-time*,
rather than having to debug the issue at run-time.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top