Click here to Skip to main content
15,902,447 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hello Experts,

I am working generating some 6 digit Random Number and that should be a Invoice Number.

But I am not sure how is that 6 digit going to be Unique always?
How does it remember all the generated Numbers so far and create a new one.
It should be always unique ...

Here is what I have tried
Protected Function Random() As Integer
    Dim RandomClass As New Random()
    Dim RememberSet As New HashSet(Of Integer)

    Dim RandomNumber As Integer

    While RememberSet.Count < 5
        RandomNumber = RandomClass.Next(0, 10)
        If RememberSet.Add(RandomNumber) Then
            RandomNumber = RandomNumber
        End If
    End While
    Return RandomNumber
End Function

Can someone help me in explaining how is this Unique? how does it remember all the generated numbers so far and it doesn't repeat it.

Ex: Few months back it generate a number like 522689

After n no of months again it shouldn't generate same 522689 Number.
Vijay Gill 27-Jan-16 11:23am    
Why random number for invoice number? Keep it sequential and every number will be unique!
sudevsu 27-Jan-16 11:32am    
Sequential like starting from 123456,123457,123458,123459 like this?
Not quite happy with that. because I have done that earlier. For some reason my VP isn't happy. Because at the End of the day this 6 digit will be a barcode on a sticker.
Vijay Gill 27-Jan-16 12:14pm    
Just like the message below, pad it with zeros on the left to get 6 digits and you are done! Now you don't need to worry about numbers being repeated and also you VP will be happy. Do you know how long before you run out of 6 digits? That could be another problem that might come back to bite you.
Konstantin A. Magg 27-Jan-16 11:45am    
If it should be an invoice number, why don't you provide ongoing numbers (000001, 000002, etc.)?

In general, by creating random numbers, you cannot be sure, that you generate a series of non-repetive items. The more numbers you generate, the higher are the chances, that you create a duplicate. That is plain mathematics.
sudevsu 27-Jan-16 11:59am    

The function makes little sense. Every time it is called it generates 5 numbers that it knows to be unique among the numbers it has generated that time it was called, and once it has generated 5 numbers it returns the last number generated, ignoring the first 4.

It doesn't have the ability to ensure numbers are globally unique, ie that it won't pick a number today that it didn't pick yesterday.
Share this answer
sudevsu 27-Jan-16 11:30am    
I understood that part. But I don't understand how it is going to remember the number it generated yesterday and make sure it won't generate it again after few days
F-ES Sitecore 27-Jan-16 11:34am    
You'll need to store the previously-generated numbers somewhere persistent like a database, or a file, or wherever.
Sergey Alexandrovich Kryukov 27-Jan-16 11:40am    
Wrong. The correct answer: it depends. The uniqueness should be enforced by such filtering for certain context. It could be the context of whole application during a single runtime session. Or it should be a set of value in some instance of some collection, unique inside this collection and not whole application. Or it should be unique in some permanent storage, then the database. But in this case, the database itself should enforce uniqueness; using HashSet would not only pointless, but also even not feasible.
F-ES Sitecore 28-Jan-16 4:19am    
It could be any of those things, it could be none of them...I simply chose to answer the question that was asked.
With random numbers, it is impossible to guaranty uniqueness and non repetitive, even if unlikely to append.

To guaranty uniqueness and non repetitive, the easiest is sequential numbers.

Are you using really the piece of code you provided ?
As I understand it, your code generate a 1 figure number which is not what you want.

Can you give us the reason of your need for a random number ?
Share this answer
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:

  1. 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).
  2. 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.

Share this answer
Why don't you use GUID?
Guid obj = new Guid();

By using Guids you avoid collision and
you don't need to reinvent the wheel.

Here is the example:

This is the format of a typical GUID:


And this is the way to produce it:
Console.WriteLine(GUID:+ System.Guid.NewGuid().ToString());

This will help:
How to generate 10 digit unique number.[^]

Please remember don't try to chop Guids.
If you just need numbers you have to check for uniqueness yourself.
And always check your requirements.
Share this answer
sudevsu 27-Jan-16 11:29am    
Can you give example?
Aria Jafarian 27-Jan-16 11:42am    
Improved the answer.
Sergey Alexandrovich Kryukov 27-Jan-16 11:45am    
This is just the common conceptual mistake: 1) Overkill, redundant 3) too much redundant data, 3) pointless, 4) strictly speaking, uniqueness is not really guaranteed; it only provides high probability of uniqueness. I never saw a theoretical proof of uniqueness and sure it simply does not exist. It does not matter though, because of items 1-3.
Aria Jafarian 27-Jan-16 11:48am    
Yes you can check for uniqueness yourself but haven't seen a collision reported in GUIDs. There was a discussion on stack and in a nutshell it is highly unlikely to see a collision because the time stamp is used in the generation of a GUID.
Sergey Alexandrovich Kryukov 27-Jan-16 12:07pm    
It does not matter. Do you understand the concept of "proof"? You don't. And your consideration of time stamp clearly shows the mistake in your logic. How about another computer? How about a computer without a network card (most important factor here)? The possibility of the clash is theoretical, but it does exist. It's theoretically impossible to guarantee absolute uniqueness, that's it.

There is an elegant discussion of the value of "check up". Consider the following statement: "all events happen before 2017". We have a lot of experimental evidence of this fact, but people have more reasons to believe that some events will happen in 2017. And it does not matter, because your advice makes no practical sense anyway.


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900