Beginner here. What is the difference between declaring an array in the global scope and using it in a method that is in the same class as the array, and declaring the array both in the global scope and in the method? The first way doesn’t work, but the second does, and I can’t find answers as to why.
string[] pettingZoo =
{
"alpacas", "capybaras", "chickens", "ducks", "emus", "geese",
"goats", "iguanas", "kangaroos", "lemurs", "llamas", "macaws",
"ostriches", "pigs", "ponies", "rabbits", "sheep", "tortoises",
};
RandomizeAnimals(pettingZoo);
void RandomizeAnimals(string[] animals)
{
if (pettingZoo.Length != animals.Length)
{
pettingZoo = new string[animals.Length];
}
Random random = new();
int randomNumber;
for (int i = 0; i < animals.Length; i++)
{
randomNumber = random.Next(0, animals.Length);
if (animals[randomNumber] == string.Empty)
{
for (int j = 0; j < animals.Length; j++)
{
if (animals[j] != string.Empty)
{
pettingZoo[i] = animals[j];
animals[j] = string.Empty;
break;
}
}
}
else
{
pettingZoo[i] = animals[randomNumber];
animals[randomNumber] = string.Empty;
}
Console.WriteLine(pettingZoo[i]);
}
}
RandomizeAnimals(pettingZoo);
void RandomizeAnimals(string[] animals)
{
string[] pettingZoo = new string[animals.Length];
Random random = new();
int randomNumber;
for (int i = 0; i < animals.Length; i++)
{
randomNumber = random.Next(0, animals.Length);
if (animals[randomNumber] == string.Empty)
{
for (int j = 0; j < animals.Length; j++)
{
if (animals[j] != string.Empty)
{
pettingZoo[i] = animals[j];
animals[j] = string.Empty;
break;
}
}
}
else
{
pettingZoo[i] = animals[randomNumber];
animals[randomNumber] = string.Empty;
}
Console.WriteLine(pettingZoo[i]);
}
}
I tried the first way and while the first iterations seemed to work (pettingZoo was being attributed the right value based on the value in animals, and animals was being attributed an empty string), but
as it progressed it would repeat values that were already empty on the animals array. While the second one, just by declaring the array inside the method (even if it was declared on the global scope, same class, same name as the array inside the method) it just worked, and I can’t explain how
Mateus Tomaz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.