Solved

C# resize and add items to an array

Posted on 2013-07-01
8
448 Views
Last Modified: 2013-07-02
Is is possible to resize an array in C#? I want to loop through an array and add items as the user adds them. So the array size will need to change each time a new item is added. I do not have any experience working with arrays. Thanks.
0
Comment
Question by:dodgerfan
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 44

Expert Comment

by:AndyAinscow
Comment Utility
Why not use a List - just add (or insert) items as required.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
You have to create a new array of the new size, then copy the items over. The Array class has a Copy method that you can use.
0
 

Author Comment

by:dodgerfan
Comment Utility
I initialize and fill the array when it starts. The program asks if the user would like to add a name. If yes, then I want to let them add a name, which means resizing the array. Array.Resize is what I was thinking. A snippet of what I have so far is below:

            Console.WriteLine("\nWould you like to add a name?");
            addName = Console.ReadLine();
            if (addName == "y")
            {
               // here is where i need to loop and resize, but I'm not sure.
                Array.Resize<string>(ref customerNames, 7);
                Console.WriteLine("Enter the name");
                customerNames[6] = Console.ReadLine();
            }
0
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
Hi dodgerfan;

I would use a List<> object because you can add and remove the objects in the List very simply and if you need to send it to a function that is expecting a Array you can use the ToArray() method on the list and it will return an array already created for you.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 44

Accepted Solution

by:
AndyAinscow earned 500 total points
Comment Utility
Is there a reason you don't want a list as I suggested earlier.  Just use .Add(new item goes here) - no need to do anything else yourself.
0
 

Author Comment

by:dodgerfan
Comment Utility
I know about the list as mentioned. I'm working through arrays and trying to get a better grip on them. I have the users picking from a list of choices. Add is one. When they want to add a name, it works, but when they enter another one the array is not displaying all of the names, even though it has increased in size. I put the switch inside a do loop.

           myChoice = Console.ReadLine();
            
           // decide what to do based on the users selection
           switch(myChoice)
           {
            case "A":
            case "a":
                  Console.WriteLine("You want to add a name.");

                  IncreaseArray(ref customerNames, 1);
                  Console.WriteLine("Enter a name to add:");
                  customerNames[6] = Console.ReadLine();

                  Console.WriteLine("The array is now holding {0} names\n", customerNames.Length);
                  Console.ReadLine();
                  Console.WriteLine("The names in the array listed alphabetically are as follows:\n");
                              for (int x = 0; x < customerNames.Length; ++x)
                              {
                                    Console.WriteLine("{0}\n", customerNames[x]);          
                              }
                  Console.ReadLine();
                  break;

the increase arrray:
       public static void IncreaseArray(ref string[] values, int increment)
       {
       string[] array = new string[values.Length + increment];
      values.CoptTo(array, 0);
      values = array;
        }
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
If you're destined to use an array, may I ask why you selected the answer that you did?
0
 
LVL 44

Expert Comment

by:AndyAinscow
Comment Utility
I agree with kaufmed - that doesn't fit with your comment adressing my question.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video discusses moving either the default database or any database to a new volume.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now