Index was out of range 🟪 .NET

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection

Code accessed a List/collection position that doesn’t exist (IndexOutOfRangeException for arrays).

Seen on: .NET

Meaning

Off-by-one loops, empty lists, or indices from another collection. Arrays throw IndexOutOfRangeException (“Index was outside the bounds of the array”).

Common causes

  • Accessing [0] on an empty list
  • Loop using <= Count
  • Index from a different collection
  • Concurrent removal

⚡ Quick fix

  1. Check Count before indexing; use FirstOrDefault
  2. Fix loop bounds (< Count)
  3. Use ElementAtOrDefault

Detailed fix by platform

C#

  1. csharp
    var first = list.FirstOrDefault();
    for (var i = 0; i < list.Count; i++) { /* ... */ }

How to diagnose

  1. Index — Value vs Count
  2. Source — Which collection?

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.