Solved

C# resize and add items to an array

Posted on 2013-07-01
8
449 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
ID: 39290250
Why not use a List - just add (or insert) items as required.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39290252
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
ID: 39290366
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
ID: 39290368
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 44

Accepted Solution

by:
AndyAinscow earned 500 total points
ID: 39290488
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
ID: 39291609
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 75

Expert Comment

by:käµfm³d 👽
ID: 39294617
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
ID: 39295570
I agree with kaufmed - that doesn't fit with your comment adressing my question.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Concerto provides fully managed cloud services and the expertise to provide an easy and reliable route to the cloud. Our best-in-class solutions help you address the toughest IT challenges, find new efficiencies and deliver the best application expe…
A company’s greatest vulnerability is their email. CEO fraud, ransomware and spear phishing attacks are the no1 threat to a company’s security. Cybercrime is responsible for the largest loss of money to companies today with losses projected to r…

911 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

23 Experts available now in Live!

Get 1:1 Help Now