2

This is a very similar problem to here c# creating new instances of a object in a for loop but my problem is unfortunately slightly different. I'm not using random either.

I have a setup similar to this:

public List<Candle> GetCandles(int can)
{
    List<Candle> dpl = new List<Candle>();

    for (int i = 0; i < can; i++)
    {
        Candle dp = new Candle();
        dp.x = new Random().Next(0000, 9999);
        dp.y = new Random().Next(0000, 9999);
        dpl.Add(dp);
    }

    return dpl;
}

My problem is that at the end of it, I don't have separate instances of candles inside. They're all the same candle for each element - despite me using "new" each time.

How do I make 100% sure that I'm putting a brand new candle into the list?

EDIT: Thanks to all that answered, but I was able to find out my own problem. Inside the class I was using, the variables were static. That meant that every single class instance had the same value. So if I set A to equal 50, all of the classes had 50.

I'm sorry if it wasn't clear, but that code wasn't mine. I'm not using random, I just posted the example because it was similar to the setup I had in my code. I had a loop and a list and was adding instances to it.

user3638162
  • 421
  • 1
  • 3
  • 12

2 Answers2

3

My problem is that at the end of it, I don't have separate instances of candles inside. They're all the same candle for each element -

Well, they are not same instances, they all have same values and the reason is the new Random().Next, you can fix that by declaring a Random instance outside the for loop and then using that for generating values.

Random random = new Random();
for (int i = 0; i < can; i++)
{
    Candle dp = new Candle();
    dp.x = random.Next(0000, 9999);
    dp.y = random.Next(0000, 9999);
    dpl.Add(dp);
}
Habib
  • 219,104
  • 29
  • 407
  • 436
1

They're all the same candle for each element - despite me using "new" each time.

No, they're not. You do have different object instances at each element, each object instance simply has the same x and y values because you're creating random numbers in a loop, all of which will have the same seed.

You can trivially see that you don't have the same object instances by mutating just one of the values after the loop and seeing that only that one is different.

Community
  • 1
  • 1
Servy
  • 202,030
  • 26
  • 332
  • 449