Why is my array of struct not resizing with Array.Resize?

500 views Asked by At

I have an array of struct's declared as

public struct classMates
    {
        public string first;
        public string last;
        public string ID;
    }

I am using StreamReader to read in a .txt file and my variables correspond to their relevant value. ie. first == first name, ID == phone number.

My array of struct is delcared as:

classMates[] classMateInfo = new classMates[43];

I have a method that is supposed to add a new member to my .txt file and append it to the end of my declared array. However, in order to do this, I will need to resize my array + 1 in order for a new member. Otherwise, it just overwrites an existing member.

I have my Array.Resize just after I call my method to add new members. However, once I've finished with that method, StreamWriting incurs and it saves it to variables ready to be written to the file.

static void addClassMates(classMates[] classMateInfo)
    {
        //I DECLARE MY ARRAY RESIZE HERE
        Array.Resize(ref classMateInfo, classMateInfo.Length + 1);
        //I am essentially creating a new space in my array for a new member, below.
        Console.Write("Enter first name: ");
        classMateInfo[classMateInfo.Length - 1].first = Console.ReadLine();
        Console.Write("Enter last name: ");
        classMateInfo[classMateInfo.Length - 1].last = Console.ReadLine();
        Console.Write("Enter phone number: ");
        classMateInfo[classMateInfo.Length - 1].ID = Console.ReadLine();

        Console.WriteLine("Would you like to save the changes back to the file? [Y/N]");
        string temp = Console.ReadLine();
        if ((temp == "Y") || (temp == "y"))
        {                
            editNumber(classMateInfo);//A method where it saves it to variables ready to be StreamWritten.
        }
    }

After that, it then moves onto a method to add it into the file. However, with slight debugging I've found there is no new added space in my array for this value I'm trying to enter. I have [42] array placeholders, and with the help of Array.Resize, this should be in actual, [43].

My question is, why is my array not being resized as I ask it to? It seems I have misplaced it, and I really have no clear as to where I should put it.

1

There are 1 answers

0
Denis  Yarkovoy On BEST ANSWER

You need to declare your method in the following way:

static void addClassMates(ref classMates[] classMateInfo)

Notice the ref for the parameter.