-1

I'm programming in c#. I have written a method to generate random imei, which has 15 numbers from 0 to 9. I combine them using StringBuilder and return the whole code as string.

public static string randomIMEIgenerator()
{
    var builder = new StringBuilder();
    while (builder.Length < 15)
    {
        builder.Append(Rnd.Next(10).ToString());
    }
    return builder.ToString();
}

Now the thing is that I want to run this method x times, because I want to generate x imei codes. Why when I write for loop I get this error?

An object reference is required for the non-static field, method, or property

My main function:

private static readonly Random Rnd = new Random();
int x = 5;
public static void Main(string[] args)
{
    for (int i = 0; i < x; i++)
    {
        randomIMEIgenerator();
    }
}

I also want to store all of those randomly generated imei's to an array. Should I just do it like that?

String[] array = new String[x];
for (int i = 0; i < x; i++)
{
    array = randomIMEIgenerator();
}

However my main question is about that error.

P.S. If I run this only one time, it generates one imei number. So the method randomIMEIgenerator is working properly.

Valdas S
  • 445
  • 1
  • 9
  • 20

2 Answers2

2

Your 'x' variable is called from a static method, so it should be static as well

 private static int x = 5;

For storing all of those imeis in an array, add the index in which you want to store the variable:

String[] array = new String[x]; 
for (int i = 0; i < x; i++) {
    array[i] = randomIMEIgenerator(); 
}

As a side note: you are not generating IMEI numbers. An imei number should end in a check digit, calculated with Luhn Algorithm

Fortega
  • 19,463
  • 14
  • 75
  • 113
1

As Fortega said, int x must be static if defined outside the main method. I would also suggest to pass the RNG to the function as parameter instead of relying on a static variable.

To assign to the array, pass the correct array index.

String[] array = new String[x];
for (int i = 0; i < x; i++) {
    array[i] = randomIMEIgenerator();
    //    ^
}

C# fiddle for this example.

Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36