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.
Not incremental but you can add and delete item how many time you want. (Maximum item should be lower than int.Max/2)
Not really, however you can use a static int which you initialize in the class and is incremented when the constructor is called.
(I hope the syntax is right, don't have a compiler here.)
If you want to have a removed robot ID being reused, don't use a counter, but use a static list and add it to the list.
However, what might be better is to keep the list of used IDs in another class, so you don't need the static at all. Always think twice before you use a static. You might keep the list of used IDs in a class called 'RobotCreator', 'RobotHandler', 'RobotFactory' (not like the design pattern).
I hope can help you !
Create a static instance variable, and use
Interlocked.Increment(ref nextId)
on it.Note #1: using
nextId++
would be valid only in non-concurrent environments;Interlocked.Increment
works even if you allocate your robots from multiple threads.EDIT This does not deal with re-using robot IDs. If you need reuse, the solution is a lot more complex: you need a list of reusable IDs, and a
ReaderWriterLockSlim
around the code that accesses that list.Note #2: If you would like to reuse smaller IDs ahead of larger IDs (as opposed to reusing IDs released earlier before IDs released later, as I coded it) you can replace
IList<int>
withSortedSet<int>
and make a few adjustments around the parts where an ID to be reused is taken from the collection.There is no such built-in functionality. You have to implement it yourself, like holding an array of bits to mark the used ids and then searching for the first unused id every time you create a new robot.
By the way, auto-increment (in a database sense) actually means that you keep incrementing the counter even if one or more of the previously used values are no longer associated to an object.
Here is some code:
There are more sophisticated algorithms / data structures to find the first unused in less than O(N), but this is beyond the scope of my post. :)
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.
And some test code for good measure.