How to generate a variable-length array in C#?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • moonriver

    How to generate a variable-length array in C#?

    I intend to generate a variable-length array, similar to link lists in plain C. For example, I define the following array

    int [] a

    Initially I assign 5 elements to the array as

    a = new int[5]
    for( k = 0; k < 5; k++
    a[k] = k

    Then I want to expand the array to 7 elements without discarding the original 5 elements. How to do


  • Lasse Vågsæther Karlsen

    #2
    Re: How to generate a variable-length array in C#?

    =?Utf-8?B?bW9vbnJpdmV y?= <xiaodan98@yaho o.com> wrote in
    news:78F44B07-77CC-4845-8FA5-EEE0DE27A6CD@mi crosoft.com:
    [color=blue]
    > I intend to generate a variable-length array, similar to link lists in
    > plain C. For example, I define the following array:
    >[/color]
    <snip>[color=blue]
    > Then I want to expand the array to 7 elements without discarding the
    > original 5 elements. How to do?[/color]

    Create a new array with the new size and copy over the existing elements.
    Then replace the existing array with the new one.

    Something like:

    Int32[] b = new Int32[7];
    Array.Copy(a, 0, b, 0, 5);
    a = b;

    You might want to look at the ArrayList class too.

    --
    Lasse Vågsæther Karlsen
    lasse@vkarlsen. no
    PGP KeyID: 0x0270466B

    Comment

    Working...