Losing values entered in the list after exiting the method (C#)

Asked

Viewed 41 times

0

Good night!

I started my learning in C# less than 3 weeks ago and I’m having trouble trying to manipulate lists. It’s a very simple console application.

I have a menu where the user selects between the options to include, edit and delete book records in the list, and also the option to print the list and clear the whole list. Each feature has a responsible method.

The problem is that when the 'Book' class records are included in the Insert() method, and when you go back to the menu and call the method to print the list, there is no output, as if the list were empty.

If I call the method to print the list within the method to include the records itself, all the values I entered in the list are displayed normally. What am I doing wrong?

                static  List <Book> Insert(){

                   List <Book>   bookList = new List<Book>();
                   Book books = new Book();

                   char reInsert;

                    do{

                    Console.Clear();

                    Console.WriteLine("Insira o titulo do livro: ");
                      
                      books.BookTitle=Console.ReadLine();

                    Console.WriteLine("Insira o nome do autor: ");
                      books.AuthorName=Console.ReadLine();
                    
                    Console.WriteLine("Insira a editora: ");
                        books.Publisher=Console.ReadLine(); 

                    Console.WriteLine("Insira o ano de lancamento: ");
                          books.ReleaseYear=Console.ReadLine();
               
                    Console.WriteLine("Insira o preco: ");
                          books.Price=decimal.Parse(Console.ReadLine());

                    Book book = new Book (books.BookTitle, books.AuthorName, books.Publisher, books.ReleaseYear, books.Price);

                    bookList.Add(book);

                    Console.WriteLine("Livro cadastrado com sucesso!");
                    Console.WriteLine("Deseja cadastrar outro livro? (S/N)");
                    reInsert=char.Parse(Console.ReadLine());
                    } while(reInsert=='s');

                    return bookList;
                                   
            }
  static void Print( List<Book> bookList){
             
             Console.Clear();

             var books = bookList.OrderBy(p => p.BookTitle);
          
                foreach(var b in books){

                    Console.WriteLine(@$"Titulo da Obra: {b.BookTitle}
                                         Autor: {b.AuthorName}
                                         Editora: {b.Publisher}
                                         Ano: {b.ReleaseYear}
                                         Valor: {b.Price}\n");
                }
                        Console.ReadLine();
                                                
                }
           }

Calling the methods:

 static bool menu = true;
        static void Main(string[] args)
        {  

            MainMenu();         
            
        }
         static void MainMenu(){
            
            do{
            Console.WriteLine("\t\t||eLib - v2.0||\n\n");

                Console.WriteLine("\t\tSelecione uma Opcao:\n");

                Console.WriteLine(@"
                
                1 - Cadastrar Livro

                2 - Editar Cadastro de Livro 

                3 - Remover um Livro

                4 - Limpar Base de Dados

                5 - Imprimir Livros Cadastrados

                6 - Sair
                
                "); 

                int index=int.Parse(Console.ReadLine());
                Options selectedOption = (Options)index;

                List<Book> bookList = new List<Book>();

                
                switch(selectedOption){

                case(Options.Insert):

                bookList =  Insert();

                break;

                case(Options.Print):

                Print(bookList);

                  break;

Hugs.

  • You are declaring the list of books within the function, so when you leave it the list will no longer exist. Try declaring the list outside the function

  • not @Natanfernandes, it can declare in the method, but it does Return. If it enters the Insert method and then Print should work. Thiago your code only has a few pieces, not to see how you are declaring the variable bookList before the switch, nor how this block is, if it stays in a loop and if it does not declare again.... put the complete code in order to understand better

  • by your code you need to declare the list bookList before the do main menu. Ai has two possibilities, with your example remove the creation from the list within the method Insert, that will delete the list, or just pass the list to the method Insert as suggested in the @Natanfernandes response

1 answer

0


Note that you are creating a new list each time you select an option in the loop. To keep the desired list you should declare the list of books out of the repeat loop.

List<Book> bookList = new List<Book>();
static void MainMenu(){
    do{
        ...
    }
}

Within its function Insert, you also create a new list. Correct, in my view would be to pass your list by parameter:

static void Insert(List<Book> bookList)
{
    Book books = new Book();

    ...

    bookList.Add(book);
}

Note that the function is now of the type void because it will not return anything, just add a book to the list that was passed. The part of the switch would look like this:

switch (selectedOption)
{
    case(Options.Insert):
        Insert(livros);
        break;

    case(Options.Print):
        Print(livros);
        break;
}
  • Natan the list can be perfectly returned by the Insert method, this may not be the problem, without seeing all the code, of how the loop and the treatment of the list can not answer accurately. Imagine that your code is inside a loop of the menu, every action of the menu will create again the list of books and this will reset the same way, your code does not solve the problem. Yes it is possible to pass the list by parameter and declare out of the method as suggested, but without seeing the loop of mine, this code will also fail

  • Got it, you think you better delete the answer or wait for the author to give some more information?

  • Good evening Ricardo and Natan, beauty? Thanks for the feedback. Correct, the method returns the list. Anyway, I had already tried to implement it the way Natan explained, but it didn’t work either. Ricardo, I edited my question with the implementation of the Mainmenu() method where I call the Insert() and Print methods()

  • Now with all the code I think you can understand the problem and correct uses reply @Natanfernandes

  • 1

    Thanks guys. @Natanfernandes, it worked. I had to declare the list Static and it worked.

  • Thanks @Ricardopunctual for the alert!

Show 1 more comment

Browser other questions tagged

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