Archive for the 'Codes' Category

21
May
09

Generating an Unique Number and String in C#

i had a trouble with one my client wantz a unique chars

in .NET we often use System.GUID to generate a unique key, but it is very long. you know when it comes to web(scenario) where it is part of the URL we need to use its string representation which is 36 characters long. It’s utterly very pathetic isn’t so ugly.

is it possible to shorten the it without loosing some of the uniqueness of the GUID, but we can come a long way if we can accept a 16 character string instead. here the magic

We can change the standard GUID string representation:

21726045-e8f7-4b09-abd8-4bcc926e9e28

Into a shorter string:

3c4ebc5f5f2c4edc

private string GenerateId()
{
     long i = 1;
     foreach (byte b in Guid.NewGuid().ToByteArray())
     {
          i *= ((int)b + 1);
     }
     return string.Format("{0:x}", i - DateTime.Now.Ticks);
}

the above method creates the shorter string and it is actually very unique. which is an iteration of 10 million, make a guess man. It won’t  duplicate. It uses the uniqueness of a GUID to create the string.

If you want numbers instead of a string, you can do that to but then you need to go up to 19 characters. The following method converts a GUID to an Int64.

private long GenerateId()
{
        byte[] buffer = Guid.NewGuid().ToByteArray();
        return BitConverter.ToInt64(buffer, 0);
}

The standard GUID is still the best way to ensure the uniqueness even though it isn’t 100% unique.

Check it, Happy Coding…




Calendar

June 2012
M T W T F S S
« Feb    
 123
45678910
11121314151617
18192021222324
252627282930  

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1 other follower


Follow

Get every new post delivered to your Inbox.