hi guys I tried to generate random numbers in a console app but my code doesn't work. Anyone who can help me fix my code? Here's mine:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            private int RandomNumber(int min, int max)
            {
            Random random = new Random();
            return random.Next(min, max); 
            }
             int returnValue = RandomNumber(5, 20);

         }



    }
}

You have placed the RandomNumber method inside the Main method, don't do that.

Also, since you are calling the RandomNumber method without having created an object of type Program, you'll either have to create an object of type Program or change the method to be static.

please show some codes sir Momerath so I can view it as an example... please please please ...

Also you create a new Random object each time you call RandomNumber. This won't cause a compilation error or anything, but it will cause RandomNumber to return the same number repeatedly when invoked multiple times in a short period of time (e.g. in a loop).

You should create a new Random object exactly once and then always use that one instance.

I didn't add anything i just re-arranged your code.

  • You can't define a method within another method.
  • Define all class instances at the top of your class.
  • Do some googling before hand, i did when i didn't know how to use Random class instead of groveling.

Hope this helps:

        Random random = new Random();

        static void Main(string[] args)
        {            
             int returnValue = RandomNumber(5, 20);
         }

         private int RandomNumber(int min, int max)
         {            
            return random.Next(min, max); 
         }
This article has been dead for over six months. Start a new discussion instead.