Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to generate ten digit alphanumeric random numbers

C#
Random rnd = new Random();
string rdnumber = "" + rnd.Next(1000, 9000);
Posted
Updated 16-Dec-15 23:17pm
v3
Comments
Patrice T 17-Dec-15 5:13am    
what is your problem ?
F-ES Sitecore 17-Dec-15 5:17am    
Google "c# generate random alphanumeric numbers" and you'll find lots of examples.
CPallini 17-Dec-15 5:27am    
What is an 'alphanumeric number'?
deepankarbhatnagar 17-Dec-15 6:23am    
You need single Alphanumeric no or multiple numbers at a time like using loop???

First, imho, it's good practice to define an instance of the Random Object at the Class root-level:

private static Random rndFunc = new Random(DateTime.Now.Millisecond);

If we assume that by "alphanumeric characters" you mean lower, and upper, case alphabet characters, and digits:
C#
private StringBuilder MakeAlphaNumeric(StringBuilder sb, int numChars)
{
    char ch;
    numChars++;

    while (sb.Length < numChars)
    {
        ch = Convert.ToChar(rndFunc.Next(48, 123));

        if (char.IsLetterOrDigit(ch))
        {
            sb.Append(ch);
        }
    }

    return sb;
}
Test:
C#
private void testMakeAlpha(int howManyStrings, int howManyCharsInString)
{
    string nchars;
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < howManyStrings; i++)
    {
        nchars = MakeAlphaNumeric(sb, howManyCharsInString).ToString();

        sb.Clear();

        Console.WriteLine(nchars);
    }
}

// call: testMakeAlpha(10,10);

// output of test
v0yINKWFYuS
E473dN68cXc
yQHnLcmC0hD
Z19JJ7Q4u2v
PCXYsFkASM5
yXeYQa1r6nj
MwiIQf4NcbN
9CKqVkvmX0M
sZ8a89xJVoI
aFpGOFMa1qG
There's some "economizing" on the use of 'StringBuilder going on here that's probably not necessary.
 
Share this answer
 
v2
Comments
Richard Deeming 17-Dec-15 15:04pm    
The documentation[^] on the Random class is slightly confusing. In the same paragraph, it recommends creating a single static instance of the class, and then tells you that you can't access it from multiple threads at the same time!

If you're going to use a static instance, you have to use a synchronization object to ensure that only one thread accesses the instance at a time. "If you don't ensure that the Random object is accessed in a thread-safe way, calls to methods that return random numbers return 0."

Stephen Toub posted some suggestions to work around this problem back in 2009:
Getting random numbers in a thread-safe way[^]
BillWoodruff 17-Dec-15 22:48pm    
Good information to be reminded of ! thanks, Bill
Andy Lanng 18-Dec-15 4:25am    
my 5*
simple:

C#
const string _availChars = "abcdefghijklmnopqrstuvwxyz0123456789";

string GenAlphaNum(int length){

      var random = new Random(); //requires seed
    return new string(Enumerable.Repeat(_availChars , length)
      .Select(s => s[random.Next(s.Length)]).ToArray());
}


You can toy with the idea of having Caps added to the list of available chars but that has the drawback of making 'A' as likely as 'a' as likely as any other single number. One way around this it to add the number string twice to even up the odds, or find some clever way of upper-casing random chars in the string.

There's loads of examples out these. This is pretty similar to a javascript version I use but I haven't tested this in C#


UPDATE:
In case you are not aware of how to add a seed - here are a couple of examples
C#
const string _availChars = "abcdefghijklmnopqrstuvwxyz0123456789";

        string GenAlphaNum(int length)
        {
            //millisecond seed
            var random = new Random(DateTime.Now.Millisecond); //requires seed
            return new string(Enumerable.Repeat(_availChars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }

with constant random
C#
const string _availChars = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random _random = null;
        Random Rand
        {
            get
            {
                if (_random == null)
                    _random = new Random(DateTime.Now.Millisecond);
                return _random;
            }
        }

        string GenAlphaNum(int length)
        {
            return new string(Enumerable.Repeat(_availChars, length)
              .Select(s => s[Rand.Next(s.Length)]).ToArray());
        }
 
Share this answer
 
v3
Comments
deepankarbhatnagar 17-Dec-15 6:25am    
This will never work for multiple generation alphanumeric numbers. This code is perfectly fine for generating single alphanumeric number
Andy Lanng 17-Dec-15 6:34am    
Sure it will. Just move the random, or pass it as a parameter and call it several times.

why not?
deepankarbhatnagar 17-Dec-15 7:28am    
NO Andy, I have tried & as I have already said it hadnot worked . although it generate alphanumeric no. but all the times it generate same number only. This is one of the loophole of Random method.
Andy Lanng 17-Dec-15 7:30am    
erm. as I stated in the solution "Requires Seed", and in my reply "move the random or pass as a parameter". These are simple things, but so is reading
deepankarbhatnagar 17-Dec-15 7:38am    
It is not working in a loop to generate support 10 alphanumeric numbers at a time as I have use your code. It gives same alphanumeric number 10 times only.

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