Generating Unique Strings And Numbers In C#
February 9th, 2008 | by programming |The best way to generate a unique key is to use System.Guid. The only problem with that is, that it generates string representations, which are 36 characters long. In many cases it is an issue, for example when using it in urls.
The standard GUID representation looks like this:
ae5e6a80-a9e9-4102-a1dd-25697336695e
And it’s generated by:
System.Guid guid = System.Guid.NewGuid()
return guid.ToString();
We can convert it to shorter string, which will still be very unique:
long j = 1;
foreach (byte b in guid.ToByteArray())
{
j *= ((int)b + 1);
}
return string.Format(”{0:x}”, j - DateTime.Now.Ticks);
What we get, is a 16 characters string:
de83a5f5bed2ea00
If we want only numbers in our id, we can use the following method:
byte[] buffer = guid.ToByteArray();
return BitConverter.ToInt64(buffer, 0);
Now we have the following ( 19 characters ):
4684493383536634496