-1

I have this code

Console.WriteLine("Distance to " + v.ToString() + ": " + v.minDistance);
List<Vertex> path = k.getShortestPathTo(v);
Console.WriteLine("Path: " + path.ToString());

v, is a Vertex, a class I have made, and prints fine. But path ends up outputting:

"Path: System.Collections.Generic.List`1[Campus.Vertex]"

Campus being my project name. How do I get this to work? In Java, the equivelant output is: Path: [T13, Three, ETB].

73est
  • 185
  • 2
  • 9
  • If it's just for the purpose of debugging, there's the `DebuggerDisplay` attribute which is handy but in this instance it would require a specialisation of your List instance, upon which the attribute would exist. [c-sharp-debugging-debuggerdisplay-or-tostring](http://stackoverflow.com/questions/3190987/c-sharp-debugging-debuggerdisplay-or-tostring) – mungflesh Apr 05 '15 at 22:21
  • Yes, it is just for debugging, Ill look into this. – 73est Apr 05 '15 at 22:22

4 Answers4

3

Try using StringBuilder

List<Vertex> path = k.getShortestPathTo(v);
StringBuilder str = new StringBuilder();

foreach(Vertex v in path){
    str.append(v);
}

Console.WriteLine("Path: " + str.ToString());
rovy
  • 2,481
  • 5
  • 18
  • 26
2

That's what .ToString() does. Unless it's overridden by a class, the default behavior on object is to simply return the name of the type. Which is the behavior you're seeing.

If you want to print out the elements of your collection, then print the elements of the collection:

List<Vertex> path = k.getShortestPathTo(v);
foreach (var x in path)
    Console.WriteLine(x);  // Maybe include some other information in the output

Note that unless Vertex overrides .ToString() then you'll just see that same behavior.

Essentially you have two options:

  1. Create classes which override .ToString() to return a meaningful string representation of their data/state. Then call .ToString() on those objects. In this case Vertex would need to override .ToString(), and also some custom containing class which holds a collection of Vertex objects would itself override .ToString(), and you'd use that containing class instead of a List<Vertext>.
  2. Write procedural code which examines into the data/state of those objects and constructs output manually.
David
  • 208,112
  • 36
  • 198
  • 279
0

path is a type List<> which is a class, thus resulting .ToString to spit out Pointer to path and not the Text you want.

For this solution you will need to create a function that iterate the list and to override a method inside Vertex ToString class to return the formattion of Vertex object.

Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
0

As an additional way to combine the Vertex-elements, you can use the string.Join method:

Console.WriteLine(string.Join(" | ", path));

The first Argument is the separator between the items and the second argument is the list. ToString() is called for every item in the list to get the string-form.

Koopakiller
  • 2,838
  • 3
  • 32
  • 47