0

I am trying to take out a random element from my array in the following code:

                char[] vs = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '|', ':', };
                string strng = null;

                Console.WriteLine(vs.Length);
                while (u <= 536870912)
                {
                    Random random = new Random();
                    random.Next(0, 51);
                    int rndm = Convert.ToInt32(random);
                    strng = strng + "" + vs[rndm];

                }
                Console.WriteLine(strng);

so whenever i try to run it it gives me an unhandled exception, here it is:

52
System.InvalidCastException: Unable to cast object of type 'System.Random' to type 'System.IConvertible'.
   at System.Convert.ToInt32(Object value)
   at ConsoleApp1.Program.Main()

the main purpose of the whole code is to generate random characters from the array, as long as it's less than 512 megabytes (which can be noticed in the code), if you have any idea please help me figure this out, thanks!

Fred
  • 11
  • Question was is already answered [here](https://stackoverflow.com/questions/14297853/how-to-get-random-values-from-array-in-c-sharp) – Tobias Cremer Dec 25 '21 at 11:01
  • 2
    `random` is your randomizer class instance and not the result of the `Next()` call, and your `Convert.ToInt32` will fail because of that. You should store the result of your `random.Next()` into a variable `int rndm = random.Next(0, 51);`. – Cleptus Dec 25 '21 at 11:02
  • Your code to generate random is incorrect. Please check this: Random random = new Random(); int rndm = random.Next(0, 51); – Anu Dec 25 '21 at 11:11
  • 3
    Because of the large iteration you should be aware that string concatenation in your scenario will perform poorly. Consider using a `StringBuilder` instead doing your test concatenation – Cleptus Dec 25 '21 at 11:34
  • I do like this one more (as a reason for closing): [How can I generate random alphanumeric strings?](https://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings) – Luuk Dec 25 '21 at 12:20
  • 1
    You never update `u`, and you may need to move that `new Random() ` line outside of the loop (so you reuse one instance) – Hans Kesting Dec 25 '21 at 12:32
  • 1
    Preallocate a 512mb char[], and then loop through assigning a new random char to each position. Turn it to a string at the end. `var arr = new char(512*1024*1024]; for(int i = 0; i < arr.Length; i++) arr[i] = vs[r.Next(vs.Length)];` – Caius Jard Dec 25 '21 at 12:48

1 Answers1

-1

You should store the return value of the random.Next() method into a variable. (The problem is that you try to cast/convert the class instance to an int.)

using System;
                    
public class Program
{
    public static void Main()
    {
        int u=0;
        
        char[] vs = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '|', ':', };
        string strng = null;

        Console.WriteLine(vs.Length);
        // just create an instance of the Random class once.
        Random random = new Random();

        while (u <= 10)
        {
            // store the random value into rndm (it's already an int)
            var rndm = random.Next(0, vs.Length);
            strng = strng + vs[rndm];
            u++;
        }
        Console.WriteLine(strng);
    }
}
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
  • 2
    Nooo.. This is a terrible way to build a 512mb string. Also, you don't need to (and shouldn't) manually seed from the clock; in old .net Random will seed itself from the clock. In new .net it doesn't (seeding from the clock is a poor idea; discourage it) – Caius Jard Dec 25 '21 at 12:47
  • Ofcourse, _"as long as it's less than 512 megabytes"_, but this answer is about pin-pointing what the problem is. Sure it is a terrible way, there are plenty better ways. This shouldn't be a string. If the seed is automatically done, i'll update the code, thanks for the addition. – Jeroen van Langen Dec 26 '21 at 00:33