2

I want to generate sequence identifiers with the int/long type in C#, but I don't want to use the databases for storing the generated values, how can I do that? Would the CPU tick counter be helpful? Or do you have any other ideas?

Sunny Chen
  • 21
  • 1

2 Answers2

0

Try this:

using Microsoft.Win32;


RegistryKey key = 
   Registry.LocalMachine.CreateSubKey ("The Right Value");

private void InitializeTheKey()
{

    this.MaxIndex = 0; // Or any other value ..

}


public Int32 MaxIndex 
{ 
   get{ return  key.GetValue("MaxIndex"); }
   set{  key.SetValue ("MaxIndex", value); } 
}

public Int32 GetNewIndex()
{

    this.MaxIndex += 1;
    return this.MaxIndex;

}

WARNING: DO NOT PLAY WITH THE REGISTRY. If you do not know what you are doing, you can cause any number of costly problems. Use this code at your own risk.

Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
0

As long as Int32 is okay, just use rand:

Random rand = new Random();
int newID = rand.Next(0, Int32.MaxValue);

Or for Int64, someone has posted an extension method you could use here: Generate random values in C#

Community
  • 1
  • 1
William Mioch
  • 917
  • 9
  • 21