0

How i'm declaring the list:

static List<String> ips = new List<String>();

Code with error:

private static String getip()
{
    lock (ips)
    {
        return ips[new Random().Next(0, ips.Count)];
    }
}

Error:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information:
Index was out of range. Must be non-negative and less than the size of the collection.

I'm quite troubled with my code had a enough of this, so i'm here seeking for some help. Answers are extremely appreciated, thank you. I've reviewed it a few times and i honestly don't know why this isn't exactly working.

Rob
  • 26,989
  • 16
  • 82
  • 98
sum1hor
  • 1
  • 3
  • 5
    It will fail when your list is empty, because it will try to select the first element (at index 0). Also, don't instantiate `Random` like that - if you call it repeatedly it will *not* be random. See [here](http://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number-in-c) – Rob Jun 14 '16 at 02:19
  • @Rob My list isn't empty mate, that part works i used the breakpoint feature earlier and saw it was being added correctly – sum1hor Jun 14 '16 at 02:22
  • Can you use a debugger to set a breakpoint and print out the random number you generate to see if the number generated is strange and lead to exception? – shole Jun 14 '16 at 02:23
  • 4
    @sum1hor Then create an example with a list with elements, and show us a scenario where it fails. Because a list with elements will not fail with the current code. Since you're using a lock - it implies you're using multi threading, so I would imagine it's due to a race condition - but I cannot be sure because you haven't shown us where you're adding elements. – Rob Jun 14 '16 at 02:24
  • Shouldn't the max value be ips.Count - 1? If the max value is the size of your array it will be out of range by 1 if it chooses that max value. – jpaugh78 Jun 14 '16 at 02:57
  • @jpaugh78 The upper bound is exclusive :) – Rob Jun 14 '16 at 02:58
  • 1
    @Rob, bah....I always forget which ones are exclusive and inclusive. My mistake. – jpaugh78 Jun 14 '16 at 02:59
  • @Blorgbeard not entirely sure this is a duplicate - as this appears to be due to a race condition, which is not covered in the wiki – Rob Jun 14 '16 at 03:13
  • 1
    @rob Maybe, but OP hasn't demonstrated any basic understanding of what the error means, or explicitly mentioned multithreading. If it is a race condition, then the question should be closed with the "insufficient code" reason. I would undo the close if OP posted a MVCE that made it clear it wasn't a dupe – Blorgbeard Jun 14 '16 at 03:19
  • @Blorgbeard Fair enough – Rob Jun 14 '16 at 03:21

0 Answers0