Home >Backend Development >C++ >How Can I Ensure Unique Random Numbers in C#?

How Can I Ensure Unique Random Numbers in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-05 21:17:411019browse

How Can I Ensure Unique Random Numbers in C#?

Seeding a Random Class for Unique Values

In your code, you have a static instance of the Random class, which generates a sequence of random numbers. However, you're encountering an issue where the same randomNumber is repeatedly obtained within a loop. This is because the Random class is initialized with a fixed seed by default, leading to predictable values.

To resolve this problem, you need to seed the Random class with a random or unique value. One effective approach is to use the GetHashCode() method of the Guid class:

Random rand = new Random(Guid.NewGuid().GetHashCode());

The Guid class generates a globally unique identifier (GUID), which can serve as a seed for the Random class. The GetHashCode() method provides a hash code of the GUID, ensuring a different seed on each invocation.

Using this approach, the Random class will generate a sequence of truly random numbers, even within a loop, eliminating duplicate randomNumber values.

The above is the detailed content of How Can I Ensure Unique Random Numbers in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn