Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# creating new instances of a object in a for loop

Tags:

c#

object

I'm trying to create a new instance of a custom object inside a for loop, if i add a breakpoint i can see the object and properties changing and it returns x number of DIFFERENT candle objects. However, if i remove the breakpoint all the objects returned in the List are the same. Any ideas?

Thanks

    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;

    }
like image 881
sam Avatar asked Jan 19 '23 23:01

sam


1 Answers

You are not seeding your random generator. You should be sharing the same random instance across all calls to next:

var randomGenerator = new Random(DateTime.Now.Milliseconds);

Then, just call the one generator:

dp.x = randomGenerator.Next(0000, 9999);
dp.y = randomGenerator.Next(0000, 9999);

This way, you've both seeded the generator with something, and each call to next should generate a new 'random' number.

like image 171
Tejs Avatar answered Jan 30 '23 22:01

Tejs