Create a C# Method to Generate Auto Increment Id

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



Leave a reply



Submit