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?
Asked
Active
Viewed 658 times
2
-
1Do you need this to be persistent? – Oded May 09 '11 at 06:06
-
1Do you need a monotonically increasing counter? – Gabe May 09 '11 at 06:09
2 Answers
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
-
2
-
I would save the MaxIndex in whatever file is going to store all those indexes. – Juan May 09 '11 at 06:26
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