Results 1 to 4 of 4

Thread: type casting error..

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2003
    Posts
    436

    Red face 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

  2. #2
    PowerPoster sunburnt's Avatar
    Join Date
    Feb 2001
    Location
    Boulder, Colorado
    Posts
    1,403

    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.

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2003
    Posts
    436

    Re: type casting error..

    thank you Sunburnt.

    But is that okay (best practices standpoint of view) to use object ?

    thanks
    nath

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    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.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width