In C #, can the storage space of an instance object allocated storage space be expanded again?

奇 卢 21 Reputation points
2022-03-16T01:28:46.393+00:00

Similar to C language, after using malloc() function, you can use realloc() function again to try to expand the memory space of the pointer. I wonder if there is a similar implementation in c#.

for example:

int[] arr=new int[10];
...

Ten int sized spaces are allocated continuously, but I want to expand the space to 11 int sizes. Can I try to expand the original space without destroying the original space?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,496 Reputation points Microsoft Vendor
    2022-03-16T02:08:23.277+00:00

    @奇 卢 , Welcome to Microsoft Q&A, you could try to use Array.Resize method to expand your array sizes.

    Here is a code example you could refer to.

            int[] arr = new int[10];  
            Console.WriteLine(arr.Length);  
            Array.Resize(ref arr, arr.Length + 5);  
            Console.WriteLine(arr.Length);  
    

    Result:

    183483-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful