I realize this question is very likely to have been asked before, but I\'ve searched around a little among questions on StackOverflow, and I didn\'t really find an answer to
I never liked integers and incremented identifiers. It makes a problem when you want to copy data across different tables (two tables same ID) or across different databases. Guid is big as a string representative and it also comes to problem when you include ids into your web application urls. So I decided to use a short string version of Guid which in the db is like varchar(16). See code bellow (method WebHash()):
public static class IdentifyGenerator
{
private static object objLock = new object();
private static char[] sybmols = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z',
};
///
/// Creates a new Unique Identity HashCode (length 16 chars)
///
///
public static string WebHash(Guid fromGuid = default(Guid))
{
lock (objLock)
return RandomString(16, (fromGuid != default(Guid) ? fromGuid.ToByteArray() : null));
}
public static string RandomString(int length, byte[] customBytes = null)
{
Stack bytes = customBytes != null ? new Stack(customBytes) : new Stack();
string output = string.Empty;
for (int i = 0; i < length; i++)
{
if (bytes.Count == 0)
bytes = new Stack(Guid.NewGuid().ToByteArray());
byte pop = bytes.Pop();
output += sybmols[pop % sybmols.Length];
}
return output;
}
}
The only disadvantage is when you create new rows in SQL. So you have to crate a similar sql function.
Will be happy to receive any critic in my address.