|
-
Apr 11th, 2006, 03:18 PM
#1
Thread Starter
Hyperactive Member
type casting error..
In an arraylist, I have some integers and some string data types.
I would like to display them on console. I am using the following code and it doesn't work.
ArrayList Simexcurve = new ArrayList();
Simexcurve.Add(8);
Simexcurve.Add("Hello world");
Simexcurve.Add(3.145678);
foreach (int n in Simexcurve)
Console.WriteLine(n.ToString());
I get an error at console.WriteLine saying "specified cast is not valid" when it tries to display "hello workd"
there is some typ casting that I should do since 'n' is declared as an int and "hello world" is a string.
can someone guide me how to display?
thanks
nath
-
Apr 11th, 2006, 03:26 PM
#2
Re: type casting error..
replace the "int" in your foreach statement with "object."
Code:
foreach (object o in Simexcurve)
Console.WriteLine(o.ToString());
Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.
-
Apr 11th, 2006, 03:27 PM
#3
Thread Starter
Hyperactive Member
Re: type casting error..
thank you Sunburnt.
But is that okay (best practices standpoint of view) to use object ?
thanks
nath
-
Apr 11th, 2006, 06:39 PM
#4
Re: type casting error..
The ArrayList contains Object references to start with. If you had added all strings or all ints then it would be OK to specify string or int as the the type of the loop element, but you can't specify int if there are strings present and you can't specify string if there are ints present, so you need to use a common base class. The only common base class between string and int is Object.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|