Search code examples
c#classidentityauto-incrementmember

C# Class Auto increment ID


I am creating a class in C# called "Robot", and each robot requires a unique ID property which gives themselves an identity.

Is there any way of creating an auto incremental ID for each new class object? So, If i created 5 new robots, their IDs respectively will be 1, 2, 3, 4, 5. If I then destroy robot 2 and create a new robot later, it will have the ID of 2. And if I add a 6th it will have the ID of 6 and so on..

Thanks.


Solution

  • This will do the trick, and operate in a nice threadsafe way. Of course it is up to you to dispose the robots yourself, etc. Obviously it won't be efficient for a large number of robots, but there are tons of ways to deal with that.

      public class Robot : IDisposable
      {
        private static List<bool> UsedCounter = new List<bool>();
        private static object Lock = new object();
    
        public int ID { get; private set; }
    
        public Robot()
        {
    
          lock (Lock)
          {
            int nextIndex = GetAvailableIndex();
            if (nextIndex == -1)
            {
              nextIndex = UsedCounter.Count;
              UsedCounter.Add(true);
            }
    
            ID = nextIndex;
          }
        }
    
        public void Dispose()
        {
          lock (Lock)
          {
            UsedCounter[ID] = false;
          }
        }
    
    
        private int GetAvailableIndex()
        {
          for (int i = 0; i < UsedCounter.Count; i++)
          {
            if (UsedCounter[i] == false)
            {
              return i;
            }
          }
    
          // Nothing available.
          return -1;
        }
    

    And some test code for good measure.

    [Test]
    public void CanUseRobots()
    {
    
      Robot robot1 = new Robot();
      Robot robot2 = new Robot();
      Robot robot3 = new Robot();
    
      Assert.AreEqual(0, robot1.ID);
      Assert.AreEqual(1, robot2.ID);
      Assert.AreEqual(2, robot3.ID);
    
      int expected = robot2.ID;
      robot2.Dispose();
    
      Robot robot4 = new Robot();
      Assert.AreEqual(expected, robot4.ID);
    }