Is there a possibility for this code to generate the same identity,
for (int i = 0; i < 20; i++)
{
string TransID = DateTime.Now.Ticks.ToString();
}
What are the considerations that make this happen?
Is there a possibility for this code to generate the same identity,
for (int i = 0; i < 20; i++)
{
string TransID = DateTime.Now.Ticks.ToString();
}
What are the considerations that make this happen?
Yes, this code can generate the same identifier.
Regardless of the tick precision, it can do so if the system date is changed in Windows and/or the Bios.
And also if it is run by computers in different time zones or if you travel.
The latter case implies that you should absolutely not use such a code even in local and not-connected applications.
If you need ID for a personnal and local application, and you never travel, this code does what you want, but it is not recommended to use such bad pattern.
As everyone says, without being wrong, you should use Guid.New()
which is actually the safest standard, or an int or a long auto-increment (for local or managed by a server) for a better performance in some cases.
https://learn.microsoft.com/dotnet/api/system.datetime.now
https://en.wikipedia.org/wiki/Unique_identifier
https://en.wikipedia.org/wiki/Universally_unique_identifier
How expensive is a GUID cast and comparison vs a string comparison
First of all, let's define what is a tick. A single tick represents one hundred nanoseconds or one ten-millionth of a second.
1 second = 10 million ticks
Basically, if you don't generate two ID's at the same time, you're OK.
Also, I would suggest you to watch GUID as an alternative. It depends on what you are trying to accomplish.
this piece of code
for (int i = 0; i < 20; i++)
{
string TransID = DateTime.Now.Ticks.ToString();
}
won't generate unique TransIDs on a computer which performs more than 10 million for loops per second.