How could you possibly expect uniqueness from a
random number generator? Don't you see that such "feature" would badly bias the "random" distribution? Of course, uniqueness is not guaranteed, period.
To choose unique set of some random values, you can filter out repeated values. One efficient way to do this in some context, it to put all unique values in the instance (in the same context) of the class
System.Collections.Generic.HashSet<>
:
HashSet(T) Class (System.Collections.Generic)[
^].
With each randomly generated value, you first check up it if is already in the set, and then either add it or keep generating random numbers until you find a new unique on. This is how:
HashSet(T).Contains Method (T) (System.Collections.Generic)[
^],
HashSet(T).Add Method (T) (System.Collections.Generic)[
^].
Pay attention how it is different from your wrong code; it's fallacy is explained in Solution 1.
Now, two recommendations for correct use of the class
System.Random
:
- Use only one instance of it in your whole application, more exactly, and application domain. Share this reference throughout your code (say, pass it to different methods).
- Initialize the instance with seeding. Use this constructor:
Random Constructor (Int32) (System)[^].
Finally look at your naming:
RandomClass
. Using the word "class" in a name of a class would already be silly, but this is not even a class, this is the instance.
—SA