Cycle Detection Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Cycle Detection runs in O(V+E) time and O(V) space, in C# as in every other language.
- ✓System.Collections.Generic gives you Dictionary<TKey,TValue> for adjacency and state, Stack<T> for the explicit iterative frame stack, and HashSet<T> when all you need is set membership rather than a state value, there is no cycle-detection algorithm in the BCL itself, though the community QuikGraph package (the maintained fork of QuickGraph) offers DAG and cycle algorithms if you would rather not hand-roll one.
- ✓Write the DFS iteratively with an explicit Stack<(int Node, int Next)>, and treat that as close to non-negotiable for any graph whose depth you do not fully control, a reviewer who has been burned by this before will flag a recursive graph traversal in C# specifically, for a reason no other mainstream managed language here shares (see pitfall).
- ✓The C# trap: A StackOverflowException in .NET cannot be caught: Microsoft's own documentation states plainly that the CLR terminates the process the moment one occurs, by design, since the runtime cannot guarantee it is safe to keep running with a corrupted native stack.
- ✓O(V+E), and Dictionary<TKey,TValue> lookups cost a hash plus equality check per access just like Java's HashMap, but because C# generics are reified rather than erased, Dictionary<int, NodeState> stores unboxed ints and enum values directly, so the autoboxing cost that hurts Java's HashMap<Integer, State> does not apply here at all.
What Cycle Detection actually is
Cycle Detection in C#: what you actually reach for
C# implementation
using System.Collections.Generic;
enum NodeState { White, Gray, Black }
static class CycleDetector
{
public static bool HasCycle(Dictionary<int, List<int>> graph)
{
var state = new Dictionary<int, NodeState>();
foreach (var node in graph.Keys) state[node] = NodeState.White;
// explicit Stack<T>: StackOverflowException from real recursion cannot be caught in .NET
var stack = new Stack<(int node, int next)>();
foreach (var start in graph.Keys)
{
if (state[start] != NodeState.White) continue;
stack.Push((start, 0));
state[start] = NodeState.Gray;
while (stack.Count > 0)
{
var (node, next) = stack.Peek();
var children = graph.TryGetValue(node, out var c) ? c : new List<int>();
if (next < children.Count)
{
stack.Pop();
stack.Push((node, next + 1));
int child = children[next];
var s = state.TryGetValue(child, out var st) ? st : NodeState.White;
if (s == NodeState.Gray) return true;
if (s == NodeState.White)
{
state[child] = NodeState.Gray;
stack.Push((child, 0));
}
}
else
{
state[node] = NodeState.Black;
stack.Pop();
}
}
}
return false;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Cycle Detection?
System.Collections.Generic gives you Dictionary<TKey,TValue> for adjacency and state, Stack<T> for the explicit iterative frame stack, and HashSet<T> when all you need is set membership rather than a state value, there is no cycle-detection algorithm in the BCL itself, though the community QuikGraph package (the maintained fork of QuickGraph) offers DAG and cycle algorithms if you would rather not hand-roll one.
What is the most common C# mistake when implementing Cycle Detection?
A StackOverflowException in .NET cannot be caught: Microsoft's own documentation states plainly that the CLR terminates the process the moment one occurs, by design, since the runtime cannot guarantee it is safe to keep running with a corrupted native stack. That makes a recursive DFS on a sufficiently deep or adversarial graph an unrecoverable process crash rather than a catchable exception, a materially worse failure mode than Java's catchable StackOverflowError or Python's catchable RecursionError, and the single strongest reason to always write this iteratively in C#.
How does Cycle Detection actually perform in C#?
O(V+E), and Dictionary<TKey,TValue> lookups cost a hash plus equality check per access just like Java's HashMap, but because C# generics are reified rather than erased, Dictionary<int, NodeState> stores unboxed ints and enum values directly, so the autoboxing cost that hurts Java's HashMap<Integer, State> does not apply here at all. Time complexity is O(V+E) and space is O(V).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.