public List<char> Columns(String input)
{
char[] temp = input.ToCharArray();
List<char> columns = new List<char>(input.Length);
for (int i = 0; i < input.Length; i++)
{
if (other.Contains(temp[i]))
{
columns.Add((char)(i+1));
}
}
return columns;
}
My goal here was to have this method return a List. However, when I went to output the contents in another method I got ‘System.Collections.Generic.List[char]
Console.WriteLine(ex.Columns(line));
That was my attempt to output it.
First, let’s answer the question of why you get
System.Collections.Generic.List[char].The method you are using to output something to the console is Console.WriteLine. If you go to the linked page you will see many overloads of that method, all taking different kinds of parameters. Let’s think which one is being used when you pass an argument of type
List<char>.If you look carefully in that list, you will see that there is no overload that takes
List<anything>. As you know, in .NET every type derives fromSystem.Object, or in other words, every type is a kind ofSystem.Object. When the C# compiler tries to choose a method overload, and it fails to resolve the exact type, it reverts to look for is a kind of relationship. In our case, the only overload that matches is the one that takesSystem.Object.So what does this overload do? If you read the description you will easily figure it out.
Okay, so when you pass your list of characters, it will call a ToString() method on it. Let’s take a look at the ToString() method on the
List<T>. When you click on the “ToString” link you will see that you end up onSystem.Object.ToString()page. This means that the List type doesn’t override the base method. So what does theObject.ToString()do?Mystery solved!
When you write
Console.WriteLine(ex.Columns(line));the compiler invokes theConsole.WriteLine(Object)overload which callsObject.ToString()on the passed parameter, which prints the fully qualified name of the type.Armed with this knowledge, you can figure out what to do in order to print the characters themselves. For example you can pass an array of characters to invoke the
Console.WriteLine(Char[])overload by writingConsole.WriteLine(ex.Columns(line).ToArray());