Home > Software engineering >  Trying to add to an array with a function in C#
Trying to add to an array with a function in C#

Time:10-08

folks. I'm just starting to learn C# and I'm trying to practice my functions/methods as well as learn about arrays, so I'm trying to write a function/method to add an item to an array. I can print out the addition from within the function/method but it's not updating the array. I figure the issue is in the function/method call but I can't seem to work it out on my own. Here's the code (Please don't judge me XD):

static void Main(string[] args)
{
   string[] mangaArray = {"Ai Yori Aoshi", "Monster Musume", "Interviews with Monster Girls"};
   AddToArray(mangaArray, "Corpse Party");
   PrintArray(mangaArray);      
}

static void PrintArray(string[] myArr)
{
    for (int i = 0; i < myArr.Length; i  )
    {
       Console.WriteLine($"[{i}] {myArr[i]}");
    }
}

static Array AddToArray(string[] myArr, string added)
{
    Array.Resize(ref myArr, myArr.Length   1);
    myArr[myArr.Length - 1] = added;
    return myArr;
}

Any feedback would be greatly appreciated. Thanks in advance. :)

CodePudding user response:

When changing myArr object inside the AddToArray method, the changes are only local and mangaArray will not be changed after returning to the Main method.

There are two approaches to address this issue.

  1. Using ref keyword: You can mark a method parameter as a reference, wich persists the changes to the object when returning from the method.
static void AddToArray(ref string[] myArr, string added)
{
    Array.Resize(ref myArr, myArr.Length   1);
    myArr[myArr.Length - 1] = added;
}
string[] mangaArray = { "Ai Yori Aoshi", "Monster Musume", "Interviews with Monster Girls" };
AddToArray(ref mangaArray, "Corpse Party");
  1. Next options is to simply assign the returned value from the method to your array.
static Array AddToArray(string[] myArr, string added)
{
    Array.Resize(ref myArr, myArr.Length   1);
    myArr[myArr.Length - 1] = added;
    return myArr;
}
string[] mangaArray = { "Ai Yori Aoshi", "Monster Musume", "Interviews with Monster Girls" };
mangaArray = AddToArray(mangaArray, "Corpse Party");

CodePudding user response:

You should pass mangaArray by reference in order to effect the changes to it:

AddToArray(ref mangaArray, "Corpse Party");

Then modify your method like this:

static Array AddToArray(ref string[] myArr, string added)
{
   Array.Resize(ref myArr, myArr.Length   1);
   myArr[myArr.Length - 1] = added;
   return myArr;
}
  • Related