.NET Framework provides built-in Guid structure which allows to generate unique identifier.
The usage is very simple and requires to callĀ NewGuid function on Guid structure.
1 |
Guid guid = Guid.NewGuid(); |
Returned object type is Guid however we can easily convert it to string.
1 |
var guidString = guid.ToString(); |
Let’s print it to screen.
1 |
Console.WriteLine(guidString); |
As the result we can see randomly generated identifier containing lowercase letters, numbers and hyphens.
1 |
e82681c2-a39e-44db-be55-e40e5503373e |
Depending on the personal requirements we can convert the Guid to different form. Let’s say uppercase letters, numbers and no hyphens.
1 |
var customGuid = Guid.NewGuid().ToString().Replace("-", "").ToUpper(); |
Above line generates new Guid, converts it to string, replaces hyphens with empty strings and makes it all uppercase.
Let’s print to console.
1 |
Console.WriteLine(customGuid); |
Result:
1 |
2F5B840745CF455B9902C0CF2BADED2A |