0
    static void Main(string[] args)
    {
        int numberOfTheWords = 1;
        string[] words = new string[numberOfTheWords];

        Console.WriteLine("You can exit from program by writing EXIT ");
        Console.WriteLine("Enter the word: ");
        for(int i = 0; i < numberOfTheWords; i++)
        {
            words[i] = Console.ReadLine(); 

            if (words[i] == "EXIT")
                break;
            else
               numberOfTheWords++;
        }
    }

Guys I am trying to expand the lengt of the array but "numberOfTheWords" variable is in the "for loop' scope" so it does not effect the global "numberOfTheWord" variable and i cannot expand the array length. What I am trying to achieve is to make dynamic array. I do not want to declare the length of the array. When the user input a word, the length of the array will be increased automatically. Can you help me about how to do this?

Derple
  • 865
  • 11
  • 28

2 Answers2

1

This can be easily done with a List.

Example:

List<string> words = new List<string>();
...
words.Add(Console.ReadLine());

Lists are dynamically expanding and you don't have to manage the size of the list on your own. The .NET Framework does that for you. You can also insert an item anywhere in the middle or delete one from any index.

bytecode77
  • 14,163
  • 30
  • 110
  • 141
0

You just need to use List:

var words = new List<string>();

An array does not dynamically resize. A List does. With it, we do not need to manage the size on our own. This type is ideal for linear collections not accessed by keys.

MRebai
  • 5,344
  • 3
  • 33
  • 52