-
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
-
Re: type casting error..
replace the "int" in your foreach statement with "object."
Code:
foreach (object o in Simexcurve)
Console.WriteLine(o.ToString());
-
Re: type casting error..
thank you Sunburnt.
But is that okay (best practices standpoint of view) to use object ?
thanks
nath
-
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.