Surendra Sharma

Surendra Sharma

Search This Blog

Tuesday, May 19, 2015

Different ways to generate unique ID in C#

In every project we need to generate some id which should be unique. I was just wondering what are the options available in .NET to achieve this?

One can go for GUID as it’s a 128 bit integer long.

       Console.WriteLine("GUID = " + System.Guid.NewGuid().ToString());
       //Output - GUID = 54f6461a-59f4-4f9f-9a67-49b18ebc6eb6

This seems to be perfect but check GUID is alphanumeric. What if we anybody want only numbers. Holy shit.

We can use random class for it as

Random random = new Random();
Console.WriteLine("Random = " + random.Next(int.MaxValue).ToString());
       //Output - Random = 1344254902

But random class has limitation of max value of integer. It can generate only 10 digit long number. Probability of generating the duplicate number is high with Random class.

Is there any other option?

Interestingly we have datetime available in C#. We can get date as well as time and can generate long number.

Console.WriteLine(System.DateTime.Now.ToString("yyyyMMddHHmmss"));
//Output – 20150519190734

Its 14 digit long number now.

You say you want longer number than this. Don’t forget milliseconds placeholder. Most interesting part of millisecond is that it’s a 7 digit long. You can use millisecond from single f to 7 times f.

Console.WriteLine(System.DateTime.Now.ToString("yyyyMMddHHmmssfffffff"));
//Output - 201505191907346290105

Its 21 digit long number now which should be unique in its own way.
Don’t be greedy. Don’t try to write “f” more than 7 times otherwise you will get “System.FormatException: Input string was not in a correct format.” Error.

Come on buddy, 21 digits long number [Correct word for this is string] is enough for us.


Let me know if you know any other way to generate it.

Please leave your comments or share this code if it’s useful for you.

No comments:

Post a Comment