Graph Creation and BFS + DFS in C#
Let's take a step back and consider the API.

Suppose I want to test the BFS traversal on different graphs.

To call GraphTraverseBFS I need to first create a BFS object. But the BFS constructor creates its own graph and runs GraphTraverseBFS on that. There is no clean way for me to just test it on my own graph.

So let's say that's fixed. Now I want to write some unit tests for GraphTraverseBFS. I can't currently do this without redirecting where the output messages are written to, and then parsing the output. This is more work than I want to do. Ideally I would be able to write something like

CollectionAssert.AreEqual(new[] { 0, 1, 2, 3 }, BFS.Traverse(graph));


The same comments hold for DFS.



List&lt;T&gt; is (generally) an implementation detail.

Graph has a public field List&lt;Node&gt; list. The fact that you're storing nodes in a List is an implementation detail, and should not be exposed to users of this code.


The user now has full access to the methods of List, and can manipulate the list however they want. This is more power than they should have.
The user can reassign the field, e.g. graph.list = null.
It locks you in to your choice of graph representation, as the user may write code that depends on list being a List.


Similar comments hold for Node.neighbors.

One pattern I like for letting the user iterate over a collection, without exposing the choice of implementation is to


Have a private readonly field with your choice of collection type (List, HashSet, etc)
Have a public IEnumerable&lt;T&gt; read-only property that exposes the collection for iteration


In code, it looks like this

public class Graph
{
    private readonly List&lt;Node&gt; nodes = new List&lt;Node&gt;();

    public IEnumerable&lt;Node&gt; Nodes
    {
        get { return this.nodes; }
    }

    ...
}




This might not be entirely suitable for you needs, but this is the sort of API I would suggest

public class Graph
{
    // Creates a new graph with `count` vertices.
    public Graph(int count)

    public IEnumerable&lt;int&gt; GetNeighbors(int node);

    public void AddEdge(int n, int m);
}

public static class BFS
{
    public static IEnumerable&lt;int&gt; Traverse(Graph graph, int startNode = 0);
}

public static class DFS
{
    public static IEnumerable&lt;int&gt; Traverse(Graph graph, int startNode = 0);
}