Search code examples
c#unity-game-engineunique

Does my GetUniqueID Method end in a Recursion Overflow?


I am currently trying to build a Method that returns a new "id" in form of an integer based on an existing Dictionary Collection with the TKey,TValue Types: int,ListButton.

I've came up with a little code so far, but I am very unsatisfied with the "testability in a certain Scenario".

My Question is as follow:

  1. Will the following Code produce a "RecursionOverflow" if the while Statement (ContainsKey(randomNumber)) hits true and returns the same Method again while the first Loop is still running since the first call provided a true Statement?

  2. Or will it return a unique number from the so called "second method call" inside the while loop and finish the first while with the return?

    private int GetUniqueID(){ 
        var randomNumber = Random.Range(0,1000); 
        while (ListButtons.ContainsKey(randomNumber)) 
        { 
            return GetUniqueID(); 
        }
        return randomNumber; 
    }  
    

Solution

  • Yes, this will "work" - until the dictionary contains a key for every value between your range. In that instance, you'll get a StackOverflowException.

    You could still get a StackOverflowException even if it's technically possible to land on a unique number - it depends on how large your range is, how many unique numbers are left, and how unlucky you are.

    Also, consider the situation where your dictionary contains every key between 0-1000 except one. It could take thousands of recursions before your random number lands on that final number.

    So yes, while this can work, this is not a great way to generate unique IDs.

    An alternative solution might be to create an ID generator class that hands out numbers sequentially by maintaining a "nextId" member and incrementing it every time it hands out an ID, a bit like how databases give IDs to records with an identity column.

    Another solution is to use GUIDs for your IDs instead of integers.