Galway,
The reason your code produces the same number is this..
Each time you call your weightItem method, you create a new instance of the Random class using the default constructor. The default constructor uses a time-dependent seed to start the random sequence. Basically it uses your system clock to seed the sequence. This wouldn't really be a problem if there was more time elapsing between each creation of a Random instance since each instance would have been seeded with a different system clock time. But since the space between each creation is so miniscule, each creation of the Random class is being seeded with the same system clock time which will give you the same "random" sequence of numbers. Each time you call random.Next(1,100), you're getting the first number of that "random" sequence.
So what you can do to fix this is a couple of things. In your Main method, you're doing a similar thing with creating a Program instance. On each iteration of your for loop, you're creating a new instance of Program. You don't need to do this.
Instead of...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication20
{
class Program
{
static void Main()
{
for(int i = 0; i < 50; i++)
{
Program instance = new Program();
Console.WriteLine("Randomly genereated number: {0}", instance.weighItem());
}
Console.ReadLine();
}
int weighItem()
{
Random random = new Random();
int num = random.Next(1, 100);
return num;
}
}
}
do this...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication20
{
class Program
{
static void Main()
{
Program instance = new Program();
for(int i = 0; i < 50; i++)
{
Console.WriteLine("Randomly genereated number: {0}", instance.weighItem());
}
Console.ReadLine();
}
Random random = new Random();
int weighItem()
{
int num = random.Next(1, 100);
return num;
}
}
}
This way you only create one instance of Program through the life of your program. You also only create one instance of Random which will also only be seeded once. This will give you a new random number.
Hope that helps.
http://msdn.microsoft.com/en-us/library/system.random.aspx