Generate unique strings and numbers in C#

by Mads Kristensen 15. March 2007 05:19

The System.Guid is used whenever we need to generate a unique key, but it is very long. That’s in many cases not an issue, but in a web scenario where it is part of the URL we need to use its string representation which is 36 characters long. It clutters up the URL and is just basically ugly.

It is not possible to shorten 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.

We can change the standard GUID string representation:

21726045-e8f7-4b09-abd8-4bcc926e9e28

Into a shorter string:

3c4ebc5f5f2c4edc

The following method creates the shorter string and it is actually very unique. An iteration of 10 million didn’t create a duplicate. It uses the uniqueness of a GUID to create the string.

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);
}

If you instead 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.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

Server-side

Comments

3/15/2007 10:24:07 AM #

 Jason Bock

Another technique is to use Base52 (upper- and lower-case letter excluding vowels plus 0-9). The reason I exclude the vowels is that it eliminates the chance of any "questionable" words being generated Smile. I used this on a previous project and it makes the Guid string representation much shorter.

Regards,
Jason

Jason Bock |

3/15/2007 10:09:15 PM #

Mike

I'm curious, do you say GUID like the word squid? Or do you say goo id? It's an ongoing argument here Smile

Mike |

3/15/2007 11:11:23 PM #

Mads Kristensen

I pronounce it "goo id" and so does all of my co-workers. I've never heard the squid pronounciation but it has a nice ring to it Smile

Mads Kristensen |

3/16/2007 1:35:55 AM #

Marty

But if the length doesn't matter? Maybe something similar to what Google uses for direct login at Gmail.

What would be the best approach for say a string of 100-200 chars and the uniqueness intact? Smile

For example a guid converted to some sort of hash string for direct login. Any suggestions? Smile

Marty |

3/16/2007 1:54:16 AM #

Mads Kristensen

@Marty. An auto login feature where the login is part of the URL, usually uses an encoded string that contains information on both the user and the account and maybe a checksum or SALT as well. You could combine two GUIDs and hash them using a SALT, then encode the SALT and add it to the two GUIDs. That would be a pretty long string of a couple hundred characters. When reading that string, you chould decode the SALT value and then use it to decode the two GUIDs.

Mads Kristensen |

3/16/2007 5:17:26 AM #

Marty

@Mads. Well, that also depends on what hash algorithm your using. Sha1 is only 40 chars, can't remember what the others are, but with sha1 you'd have to have a really long salt key to get over 100 or 200 chars..... if I understood your suggestion correctly Smile

Marty |

3/16/2007 5:29:50 AM #

Mads Kristensen

@Marty. If I put two GUID's into the same 32 byte array and encrypt them using RijndaelManaged class, I get a 128 character base64 string. Then encrypt the SALT and add it as well and you are around the 200 characters.

Mads Kristensen |

3/19/2007 11:59:55 PM #

 Michal Talaga

For random strings I usually do something like:

Guid.NewGuid().GetHashCode().Replace("-", "n");

It only works one way, but most of the times it is all I need.

Michal Talaga |

3/20/2007 12:06:14 AM #

Mads Kristensen

The problem with your approach Michal, is that the GetHashCode() method of the Guid class isn't unique as the Guid is.

Mads Kristensen |

10/1/2007 2:20:56 AM #

pingback

Pingback from rtipton.wordpress.com

Generating a GUID in C# « Rhonda Tipton’s WebLog

rtipton.wordpress.com |

2/7/2009 5:21:33 PM #

James

Thanks for the article.

James India |

2/11/2009 9:14:32 PM #

trackback

On The Road Knowledge – uniqueId und ToLower()

Wenn man an einem Projekt sitzt, möchte man sich und anderen immer wieder gerne Arbeit ersparen und CodeSnippets

Aus dem Leben eines Developer Evangelisten |

2/11/2009 9:18:20 PM #

Jan Schenk

Hi Mads,
I used your code snippet for a project, blogged about it and referred to this article for origin of snippet.
Hope thats ok!
Thanks for that fine work!
jan

Jan Schenk Germany |

2/11/2009 9:25:43 PM #

pingback

Pingback from clickandsolve.com

C# On The Road Knowledge – uniqueId und ToLower() - Click & Solve

clickandsolve.com |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008