There are a few things to do here.
1) Move the definition of randNum to class level - do not generate a new instance each time you want a random number. Since the new instance is initialized partly from the time, this will reduce the chances of getting the same sequence repeated.
2) Don't use NextDouble, then multiply it by the length. Instead, use a random int instead:
Random.Next[
^]
private Random randNum = new Random();
public static string createRandomString(int Length)
{
string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
int outputLength = randNum.Next(Length);
char[] chars = new char[outputLength];
for (int i = 0; i < outputLength; i++)
{
chars[i] = _allowedChars[randNum.Next(allowedChars.Length)];
}
return new string(chars);
}
"in this
private Random randNum = new Random();
public static string createRandomNumbers()
{
int Length=5;
string _allowedChars = "0123456789";
int outputLength = randNum.Next(Length);
char[] chars = new char[outputLength];
for (int i = 0; i < outputLength; i++)
{
chars[i] = _allowedChars[randNum.Next(allowedChars.Length)];
}
return new string(chars);
}
it didnt take my length and produce duplicate code"
"how to rectify this i want to generate unique number in lenght = 5"
Then do it the easy way:
private static Random randNum = new Random();
public static string createRandomString()
{
return randNum.Next(100000).ToString("00000");
}
Which will return a 5 character string with a random number in it.