Daniel, your method of
public void GenerateList(int Length)
has an important problem. Because the local variable Numbers
is never used, in fact. It has an allocated memory like a List<int>
, is assigned a new List<int>
, and this list is populated by the method. But with this local variable, you would either use it within the method itself, or there’s no point in having it.
By the result you want, to be able to access the list from outside the class, there are at least two ways to change your code to allow this.
First Form
The first has already been addressed by Maniero: changing the signature of the method to:
public List<int> GenerateList(int Length)
and, completing his code, the body of the method would be:
{
var numbers = new List<int>();
for (int c = 0; c < Length; c++) {
Console.WriteLine("Qual é o {0}º número da lista?",count);
numbers.Add(int.Parse(Console.ReadLine())
}
return numbers
}
The question here is return
making that, when you invoke the method from within Main
, the call return the list. So, in order to use this list, you would only need to create a local variable in Main
, and assign it with the return of the method GenerateList
, thus (within Main
):
List<int> listaLocal = insertList.GenerateList(ListLength);
From there you can access this list as you wish.
Second form
Another way you can access the list created by GenerateList
, is to declare the list as a class property ListMethod
.
Thus, the class ListMethod
should look like:
public class ListMethod
{
...
public List<int> Numbers { get; set; }
...
public void GenerateList(int Length)
{
int count = 1;
for(int c = 0; c < Length; c++)
{
Console.WriteLine("Qual é o {0}º número da lista?",count);
Numbers.Add(int.Parse(Console.ReadKey())
count++;
}
}
}
Hence, your call in Main
would be the same as before, and you could access the list while the object is within the scope. If the instantiation of ListMethod
is from within Main
, you will be free to access it:
Main()
{
...
insertList.GenerateList(ListLength);
List<int> listaLocal = insertList.Numbers;
...
}
Thanks! The problem was the lack of "public" keyword, with it I got the method to return the list values.
– Stacklysm