CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Unique Id Generation

258 Views
Copy Code Show/Hide Line Numbers
/// <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);
}
by Rick Strahl
  July 09, 2009 @ 4:21pm
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.

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate