man22 - 1 year ago 60
C# Question

# My code only works properly in 'step into' and not normally

Basically i want my code to generate two random numbers and then what they equal. It works how it should when i go into step into but not normally and i can't for the life of me figure out why! when i run it normally the two numbers are always the same, however when i step into the program they are different. I want them both to be random. I'm using visual studio 2015 if that helps.
Thank you in advance!

``````class Program
{
static void Main(string[] args)
{
DiceRoll DR = new DiceRoll();
DR.SecondRolledDice();
}
}

public int RolledDice()
{
Random numberGenerator;
numberGenerator = new Random();
int firstdiceroll = numberGenerator.Next(1, 7);

return firstdiceroll;
}

public void SecondRolledDice()
{
Random SecondnumberGenerator;
SecondnumberGenerator = new Random();
int seconddiceroll = SecondnumberGenerator.Next(1, 7);

DiceRoll DR = new DiceRoll();
var diceroll = DR.RolledDice();

string NumberName;
string NumberNameTwo;
string sum;
string[] SecondNumberNames;
SecondNumberNames = new string[12] { "One", "Two", "Three", "Four", "Five", "Six", "seven", "eight", "Nine", "ten", "eleven", "twelve"};

NumberName = SecondNumberNames[seconddiceroll - 1];
NumberNameTwo = SecondNumberNames[diceroll - 1];
sum = SecondNumberNames[(diceroll + seconddiceroll) - 1];

Console.WriteLine("{0} Plus {1} Equals {2} ", NumberName, NumberNameTwo, sum);
}
``````

Answer Source

From System.Random documentation:

The Random() constructor uses the system clock to provide a seed value. This is the most common way of instantiating the random number generator.

If the same seed is used for separate Random objects, they will generate the same series of random numbers.

Also, from the Avoiding multiple instantiations section:

Initializing two random number generators in a tight loop or in rapid succession creates two random number generators that can produce identical sequences of random numbers. In most cases, this is not the developer's intent and can lead to performance issues, because instantiating and initializing a random number generator is a relatively expensive process.

Both to improve performance and to avoid inadvertently creating separate random number generators that generate identical numeric sequences, we recommend that you create one Random object to generate many random numbers over time, instead of creating new Random objects to generate one random number.

You need to instantiate random once, then call `Next` method for both dice.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download