C#
graph data structure
data structures
programming
software development

Is there any graph data structure implemented for C

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

C# does not include a built-in graph type in the base class library. Instead, developers usually model graphs with general-purpose collections such as Dictionary, List, and HashSet, or they bring in a library when they need specialized algorithms.

What A Graph Needs In Practice

A graph is a set of vertices connected by edges. The representation depends on the operations you care about:

  • adjacency lookup for traversal
  • edge weights for path-finding
  • directed versus undirected edges
  • fast insertion versus compact storage

For most application code, an adjacency list is the right starting point. It is easy to read, memory-efficient for sparse graphs, and works naturally with traversal algorithms such as BFS, DFS, and Dijkstra.

A Simple Graph Implementation In C#

The example below builds a directed graph using an adjacency list. It supports adding vertices, adding edges, and returning neighbors.

csharp
1using System;
2using System.Collections.Generic;
3
4public class Graph<T>
5{
6    private readonly Dictionary<T, List<T>> _adjacency = new();
7
8    public void AddVertex(T vertex)
9    {
10        if (!_adjacency.ContainsKey(vertex))
11        {
12            _adjacency[vertex] = new List<T>();
13        }
14    }
15
16    public void AddEdge(T from, T to)
17    {
18        AddVertex(from);
19        AddVertex(to);
20        _adjacency[from].Add(to);
21    }
22
23    public IReadOnlyList<T> GetNeighbors(T vertex)
24    {
25        return _adjacency.TryGetValue(vertex, out var neighbors)
26            ? neighbors
27            : Array.Empty<T>();
28    }
29}

Usage is straightforward:

csharp
1var graph = new Graph<string>();
2graph.AddEdge("Toronto", "Montreal");
3graph.AddEdge("Toronto", "Ottawa");
4graph.AddEdge("Ottawa", "Montreal");
5
6foreach (var city in graph.GetNeighbors("Toronto"))
7{
8    Console.WriteLine(city);
9}

That is often enough if you only need connectivity and traversal.

Traversing The Graph

Once you have an adjacency list, adding algorithms becomes simple. Here is a breadth-first traversal that visits reachable nodes in layers.

csharp
1using System;
2using System.Collections.Generic;
3
4public static class GraphAlgorithms
5{
6    public static IEnumerable<T> BreadthFirst<T>(Graph<T> graph, T start)
7    {
8        var visited = new HashSet<T>();
9        var queue = new Queue<T>();
10
11        visited.Add(start);
12        queue.Enqueue(start);
13
14        while (queue.Count > 0)
15        {
16            var current = queue.Dequeue();
17            yield return current;
18
19            foreach (var neighbor in graph.GetNeighbors(current))
20            {
21                if (visited.Add(neighbor))
22                {
23                    queue.Enqueue(neighbor);
24                }
25            }
26        }
27    }
28}

This design keeps the data structure small and lets algorithms live in separate classes.

When A Library Makes Sense

If you need more than a few traversal methods, using a library can save time. Historically, developers have used projects such as QuikGraph for graph algorithms and graph models in .NET ecosystems. The exact package choice depends on maintenance status and your target framework, so check current compatibility before depending on one.

A library is useful when you need features such as:

  • topological sort
  • minimum spanning tree
  • weighted shortest paths
  • graph serialization
  • mature test coverage for edge cases

If your needs are simple, a custom adjacency-list implementation is usually easier to maintain than pulling in a large dependency.

Choosing The Right Representation

An adjacency list is ideal for sparse graphs, which covers many business problems such as dependencies, routes, and workflows. An adjacency matrix is only attractive when the graph is dense and vertex counts are fixed, because it uses much more memory.

For weighted edges, store an edge object instead of a raw neighbor value:

csharp
public record Edge<T>(T Target, int Cost);

Then change the adjacency map to Dictionary<T, List<Edge<T>>>. That small change opens the door to shortest-path algorithms without redesigning the rest of the code.

Common Pitfalls

The first mistake is expecting a built-in Graph class in the standard library. There is none, so search results often mix custom examples, abandoned libraries, and visualization packages. Decide first whether you need a data structure, an algorithm library, or a graph drawing tool.

Another common issue is overengineering too early. Many codebases only need a directed adjacency list and one traversal method. Building a generic framework with dozens of abstractions before the use case is clear adds complexity without real benefit.

Be careful with equality semantics as well. If you use custom objects as vertices, make sure equality and hashing behave correctly. Dictionary and HashSet depend on those rules.

Finally, do not store everything in one giant mutable object if concurrency matters. Graph algorithms are easier to reason about when the graph is immutable during traversal.

Summary

  • C# has no built-in graph data structure in the base class library.
  • The usual starting point is an adjacency list backed by Dictionary and List.
  • A small custom implementation is enough for many traversal and routing tasks.
  • Add edge objects when you need weights or richer metadata.
  • Use a library only when you need advanced algorithms or features beyond a basic graph model.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.