Assign Incrementing uint ID in constructor in C#

216 Views Asked by At

I have a class that supposedly handles generation of a unique ID of uint type. However upon multiple use, the uint value does not seem to increment.

static class UniqueIdGenerator
    {
        public static uint nextUnique;

        public static uint GetNextUnique()
        {
            nextUnique++;
            return nextUnique;
        }
    }

This class is used to assign a unique integer ID whenever it's called on other classes. e.g. both of the sample constructors below have an ID property that's supposed to get its value from the UniqueIdGenerator class

 public Car()
     {
        carNumber = UniqueIdGenerator.GetNextUnique();
     }

public Boat()
     {
        boatNumber = UniqueIdGenerator.GetNextUnique();
     }
1

There are 1 best solutions below

2
On

The code posted should work, as far as I can tell. It does come with troubles though.

The first trouble is thread safety. Two threads can attempt to increment the same value and result in having the same ID. To fix this use Interlocked.Increment(ref nextUnique)

The second potential trouble is a security one - incremental IDs can lead to web APIs that are easy to scrape. Zoom had a similar problem last year with their meeting IDs if I remember correctly.

If you need IDs using a GUID solves both the problems and it comes with the added benefit of not having to worry too much about IDs colliding in a distributed system:

public class MyBusinessObject
{
  public Guid ID {get; private set;} = Guid.NewGuid();
}

The private set is to enable deserializing, while prohibiting directly setting the value in code.

I realize this is too much for what you probably see as a very simple question, but ignoring the hidden complexities can lead to getting hacked down the road.

Cheers!