How to access the elements of a list declared in a different class?

Asked

Viewed 1,181 times

1

I have developed a code that generates a list when the following input data is informed:

  • List size (or how many "Indexes")

  • The values that will fill the said "Indexes".

Values are collected within a method entered in the public class "Listmethod". I would like to be able to access them later after filling in. Follow the code below.

Declaring the method (outside the Main())

public void GenerateList(int Length)
{   
         int count = 1;

         List<int> 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.ReadKey())
               count++;
          }
}

Using the method (within the Main())

        ListMethod insertList = new ListMethod();

        Console.WriteLine("Qual é o tamanho da lista?");
        int ListLength = int.Parse(Console.ReadLine());

        insertList.GenerateList(ListLength);

        Console.ReadKey();

3 answers

2

You have to return the list so that the consumer can use it. So:

using static System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main() => ListMethod.GenerateList(5);
}

public static class ListMethod {
    public static List<int> GenerateList(int length) {
        var numbers = new List<int>(length);
        for (int c = 0; c < length; c++) {
            WriteLine($"Qual é o {c + 1}º número da lista?");
            if (!int.TryParse(ReadLine(), out var number)) {
                WriteLine("Valor digitado errado, digite novamente");
                c--;
                continue;
            }
            numbers.Add(number);
        }
        return numbers;
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Note that in the form shown it makes no sense that this method is an instance of a class. I don’t even know if it needs to be another class.

If there is something that is not in the question that makes sense to have an instance, then a lot needs to be changed, it is not enough this.

Note that I simplified, optimized and modernized the code, and checked whether the typing was successful to not let the program break. Maybe I could use one array instead of the list in this case.

I also fixed the reading that is always done with the ReadLine(), the ReadKey() serves for something else and will not function as expected in this case.

There are other things that could possibly be better, but it depends on context that we don’t have.

Who knows a while was better than a for in this case.

1


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.

0

Every time you create a new instance of Listmethod with its list inside you initialize everything from scratch.

It depends a lot on the scenario, but if Voce wants to fill a list, and leave it in memory for your application to consume that list later (while running) an option is you use the Memorycache

You create a cache with a Key and then return it through the same Key. Add reference to:

System.Runtime.Caching;

  var cache = MemoryCache.Default;
  var obj = new List<int> {1, 2};

  cache.Set("Key", obj, null);

  var lstfromCache = (List<int>)cache.Get("Key");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.