Results 1 to 2 of 2

Thread: Easy array question

  1. #1

    Thread Starter
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Easy array question

    Can someone show me how to declare, initialise and fill an array of class objects when I don't know how many objects I need at the time. Could be 10, could be 1000, there is no way of checking beforehand.

    This would be blissfully simple in VB because of Redim, but C# has to be a pain in the arse doesn't it

    Help!
    I don't live here any more.

  2. #2
    Addicted Member
    Join Date
    Aug 2000
    Location
    Nottingham, England
    Posts
    197
    In C#, you can't declare an array, size it, add elements to it, and then resize it while keeping the original elements, as you could using Redim Preserve in VB.

    There are two options - if you know how many items you are going to need in total before you start adding items, then do this:

    Code:
    string[] mValues;
    
    int i = 10; //Get the number of values here.
    
    mValues = new string[i];
    
    mValues[0] = 123;
    //etc...
    If you don't know how many items you will need in total until after you've started adding elements, then don't use an array. You need to use the C# equivalent of a collection. The best one to use would probably be an ArrayList.

    Code:
    ArrayList mValues = new ArrayList();
    
    mValues.Add("321321");
    //etc...
    
    //To get the values back, cast them:
    MessageBox.Show((string)mValues[0]);
    Hope this helps!

    Steve.
    Sent by: Steve Barker
    E-mail: [email protected]

    P.S. I KNOW 1 is not a prime!
    See this thread: http://forums.vb-world.net/showthread.php?threadid=26485

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