C# Class Auto increment ID
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);
}
How to generate and auto increment Id with Entity Framework
This is a guess :)
Is it because the ID is a string? What happens if you change it to int?
I mean:
public int Id { get; set; }
How can I manually set an ID for an AUTOINCREMENT column using a designer-generated DataTable?
You'll have to either use an auto-incrementing value, or set it yourself. There is no option to do both.
Related Topics
Truncate Two Decimal Places Without Rounding
Best Way to Check If a Data Table Has a Null Value in It
What Is the Purpose of a Question Mark After a Type (For Example: Int Myvariable)
Windows Service Cannot Access Network Location (Unc) Path
Redirecting to Another Page in ASP.NET MVC Using Javascript/Jquery
Split a Comma-Separated String With Both Quoted and Unquoted Strings
How to Implement Async Task to Fetch Data from Database Using Async and Await
Select Multiple Fields Group by and Sum
C# Find Highest Array Value and Index
Client Specific Role Based Authentication
How to Generate Getters and Setters in Visual Studio
Convert String to Given Regex Pattern
Setting Connection String With Username and Password in Asp.Core MVC
Deserialize Json Array to C# List Object