0

Keep getting the following message when printing a list on console.

System.Collections.Generic.List`1[System.Int32]

This is the console code. It is designed to generate a Fibonacci sequence of a given length. I have tried using the ToString() method, but that doesn't work either. I have built the algorithm in Java so i know that the issue, is fundamentally a C# problem. The issue is resolved if print i print the list elements individually, but i can't print the whole list.

class Program
{
    public static void Main(string[] args)
    {
        Fibonacci fibo = new Fibonacci();


        Console.WriteLine(fibo.getSequence(9));

        Console.ReadLine();
    }
}

class Fibonacci
{

    public List<int> getSequence(int length)
    {
        List<int> results = new List<int>();

        results.Add(1);
        results.Add(1);

        int counter = 0;

        while (counter != length - 2)
        {
            int num1 = results[results.Count - 1];
            int num2 = results[results.Count - 2];

            results.Add(num1 + num2);
            counter++;
        }

        return results;
    }
}
Lennart
  • 9,657
  • 16
  • 68
  • 84
Edmund
  • 63
  • 8
  • Possible duplicate of [How to display list items on console window in C#](https://stackoverflow.com/questions/759133/how-to-display-list-items-on-console-window-in-c-sharp) – Brank Victoria Oct 10 '18 at 09:44

3 Answers3

2

You're returning a List<int>. To print it, you have to e.g. iterate over it

foreach(var i in fibo.getSequence(9)) {
    Console.WriteLine(i);
}

Or you can use String.Join()

Console.WriteLine(String.Join(" ", fibo.getSequence(9)));
adjan
  • 13,371
  • 2
  • 31
  • 48
1

You are trying to print the object directly to console try iterating over list and print them wherever returned.

for (var item in returned) 
   Console.WriteLine(item)

if using a custom Type. keep in mind that you have defined its to string method.

0

Change your Main() to read:

        public static void Main(string[] args)
        {
            Fibonacci fibo = new Fibonacci();

            foreach(var element in fibo.getSequence(9))
            {
                 Console.WriteLine(element);
            }

            Console.ReadLine();
        }

Explanation

Look at what you're passing to Console.WriteLine() in your example. getSequence() is returning a list, so you're passing a list to WriteLine(). WriteLine will ToString() on the collection which, by default, will render out the type. If you pass it each individual element (int), it will call ToString() on each one and give you the number.

This is based on the assumption that you want a line per element. If not, look into using String.Join