CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: array again

  1. #1
    Join Date
    Feb 2003
    Location
    Philippines
    Posts
    168

    array again

    what should I do if i want to insert a object type variable in an string array?
    Last edited by peevee12; July 1st, 2004 at 08:14 AM.
    ------ Human Knowledge Belongs to the World ------

  2. #2
    Join Date
    May 2003
    Location
    Germany
    Posts
    936
    If that object is a string do a type cast.
    If not forget your string array and take an ArrayList. There you can store objects and strings are objects too.

  3. #3
    Andy Tacker is offline More than "Just Another Member"
    Join Date
    Jun 2001
    Location
    55°50' N 37°39' E
    Posts
    1,503
    yeh, torrud is right.
    use arraylist which will ease the storage.
    when you need to retrieve simply cast the output to the desired one.
    If you think you CAN, you can, If you think you CAN'T, you are probably right.

    Have some nice Idea to share? Write an Article Online or Email to us and You may WIN a Technical Book from CG.

  4. #4
    Join Date
    Apr 2004
    Location
    Oregon, USA
    Posts
    40
    :0)

    using System.Collections; // For ArrayList Enabled

    ArrayList myList = new ArrayList;
    myList.Add("This is a string");
    myList.Add(3453);

    string myString = (string)myList[0];
    int myInt = (int)myList[1];


    Happy coding!

  5. #5
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940
    Be careful with ArrayList.

    It's not typesafe, so you can store anything in it.

    I recommend having a seperate class which has an array list as a member variable to make sure you don't accidentally add something wrong to it.

    Either that or do this :

    Code:
    ArrayList aList;
    aList.Add("Hello");
    aList.Add(200);
    
    // put a try catch for this 
    
    string sItem = null;
    
    try
    {
          sItem = aList[0] as string;
    }
    catch (InvalidCastException)
    {
        // you know now that it wasn't a string
    }
    Otherwise you might get caught out !

    Darwen.
    Last edited by darwen; July 4th, 2004 at 05:06 PM.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

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

Featured