001
001

Reputation: 65205

Generate a unique number without database

How do I generate a unique number in c# without the database?

(max 17 digits).

EDIT: digits only.

Upvotes: 2

Views: 2670

Answers (2)

vinayak
vinayak

Reputation: 64

You can use GUID, A GUID (Globally unique identifier) is a 128-bit integer that can be used to uniquely identify something.

System.Guid.NewGuid()

Upvotes: 0

Richard Fawcett
Richard Fawcett

Reputation: 2819

You could take a look at Twitter's open source Snowflake project for inspiration, which solves a similar problem. It's written in Scala, but a simplified version is quite simple to code in C#.

The premise is to get the current timestamp, and bitwise shift it left, leaving the right-hand bits available for a simple sequence number, which is reset to 0 every time the timestamp increments.

By playing around with the bit lengths, and altering the granularity of your timestamp (e.g. decide whether to use seconds or milliseconds), you should be able to produce something which can fit into 17 digits quite simply.

Upvotes: 6

Related Questions