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

1

I've developed code that generates a list when the following input data is entered:

  • Size of the list (or how many " Indexes")

  • The values that will populate the " Indexes ".

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

Declaring the method (out of 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 Main() )

        ListMethod insertList = new ListMethod();

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

        insertList.GenerateList(ListLength);

        Console.ReadKey();
    
asked by anonymous 03.11.2017 / 22:58

3 answers

1

Daniel, your method

public void GenerateList(int Length)

has a major problem. Because the local variable Numbers is never used, in fact. It has a memory allocated as a List<int> , is assigned a new List<int> , and this list is populated by the method. But with this local variable, either you would use it within the method itself, or there is no reason to have it.

For the result you want, to be able to access the list 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 the return causing, when you invoke the method from within Main , the call returns the list. So, for you to be able to use this list, you would just need to create a local variable in Main , and assign it with the return of the GenerateList method, so (within Main ):

List<int> listaLocal = insertList.GenerateList(ListLength);

From here 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 property of class ListMethod .

So, the ListMethod class 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 on Main would be the same as before, and you could access the list while the object is within the scope. If the ListMethod instantiation is within Main , you are free to access it:

Main()
{
    ...
    insertList.GenerateList(ListLength);
    List<int> listaLocal = insertList.Numbers;
    ...
}
    
05.11.2017 / 14:47
2

You have to return the list for the consumer to use. So:

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

public class Program {
    public static void Main() {
        var lista = 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;
    }
}

See running on .NET Fiddle . And in Coding Ground . Also I placed GitHub for future reference .

Note that in the form shown it does not make sense for this method to be an instance of a class. I do not know if it needs to be another class.

If you have something that is not in the question that makes sense to have an instance, a lot of things need to be changed, this is not enough.

Please note that I simplified, optimized, and modernized the code, as well as verifying that typing was successful so as not to let the program crash. Maybe I could use an array instead of the list in this case.

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

There are other things that could possibly be better, but it depends on the context that we do not have.

Maybe a while would be better than a for in this case.

    
03.11.2017 / 23:09
0

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

It depends a lot on the scenario, but if you want to populate a list, and leave it in memory for your application to consume that list later (during execution) one option is to use 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");
    
03.11.2017 / 23:05