Language: C#
Unique Id Generation
/// <summary> /// Generates a unique Id as a string of up to 16 characters. /// Based on a GUID and the size takes that subset of a the /// Guid's 16 bytes to create a string id. /// /// String Id contains numbers and lower case alpha chars 36 total. /// /// Sizes: 6 gives roughly 99.97% uniqueness. /// 8 gives less than 1 in a million doubles. /// 16 will give full GUID strength uniqueness /// </summary> /// <returns></returns> /// <summary> public static string GenerateUniqueId(int stringSize) { string chars = "abcdefghijkmnopqrstuvwxyz1234567890"; StringBuilder result = new StringBuilder(stringSize); int count = 0; foreach (byte b in Guid.NewGuid().ToByteArray()) { result.Append(chars[b % (chars.Length - 1)]); count++; if (count >= stringSize) return result.ToString(); } return result.ToString(); } /// <summary> /// Generates a unique Id with 8 characters made up of /// numbers and lower case alpha characters. /// </summary> public static string GenerateUniqueId() { return GenerateUniqueId(8); } /// Generates a unique numeric ID. Generated off a GUID and /// returned as a 64 bit long value /// </summary> /// <returns></returns> public static long GenerateUniqueNumericId() { byte[] bytes = Guid.NewGuid().ToByteArray(); return BitConverter.ToInt64(bytes, 0); }
Tags:
Description:
Another shot at unique Ids. This version allows control over how the number of input values used for id generation. The non-specific constructor defaults to 8 which is the sweet-spot where less than 1 in a million is a duplicate. 16 will get you full GUID strength.
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

