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?

2
  • 1
    Do you need this to be persistent? Commented May 9, 2011 at 6:06
  • 1
    Do you need a monotonically increasing counter? Commented May 9, 2011 at 6:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And it will reset when the application restarts.
I would save the MaxIndex in whatever file is going to store all those indexes.
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#

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.