Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

resize an array in the method in c#

Please think we have a method called AddArr that takes an array and several values and adds those values to the array.

like this

c# code

    public static void AddArr(string[] nums, params string[] n)
    {
        string[] l = new string[nums.Length + n.Length];
        int j;
        for (j = 0; j < nums.Length; j++)
        {
            l[j] = nums[j];
        }
        for (int h = 0; h < n.Length; h++, j++)
        {
            l[j] = n[h];
        }
        Array.Resize(ref nums, l.Length);
        for (int f = 0; f < nums.Length; f++)
        {
            nums[f] = l[f];
        }
    }

but for line 13

Array.Resize(ref nums, l.Length);

it only resize string[]nums the entry parameter of method an it isn't resize the real Array for E.g please think we have a program like this

        string[] names = new string[3] { "Parsa", "Nikan", "Neda" };
        AddArr(names, "Alex");
        foreach (var val in names)
        {
            Console.WriteLine(val);
        }
        Console.WriteLine(names.Length);

after running program you can see the output is

Parsa
Nikan
Neda
3

Alex name has not been added to the array

if you set a break point in the Method you can see after compiling line 13 of method the the nums(parameter in the method) It is resized but when the compiling of method was end you can see names(the Array) wasn't resized but I was able to fix this problem myself by writing code in the Main method but I want to write this code in a separate method and I do not want to use lists

question from:https://stackoverflow.com/questions/65904930/resize-an-array-in-the-method-in-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
string[] names = new string[3] { "Parsa", "Nikan", "Neda" };
string[] names2 = new string[1] { "Alex" };

var newArray = new int[names.Length + names2.Length];

names.CopyTo(newArray , 0);
names2.CopyTo(newArray , x.Length);

or you can create a method:

public static string[] AddArr(string[] names, string[] names2)
{
    var newArray = new int[names.Length + names2.Length];

    names.CopyTo(newArray , 0);
    names2.CopyTo(newArray , x.Length);

    return newArray;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...