I’m trying to generate a random Product list using the following method, but I’m getting the same Product instance multiple times.
Output for count 5:
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
Name: Qmlcloboa Price: 3.608848
I read on List type being a reference type & it overwrites stuff. Below is my code. am I missing something which could give me unique Product instances? Thanks & I would appreciate your help.
public List<Product> ProductGroupGenerator(int count)
{
List<Product> pList = new List<Product>();
for (int i = 0; i < count; i++)
{
Random r = new Random();
string alphabet = "abcdefghijklmnopqrstuvwyxzeeeiouea";
Func<char> randomLetter = () => alphabet[r.Next(alphabet.Length)];
Func<int, string> makeName =
(length) => new string(Enumerable.Range(0, length)
.Select(x => x == 0 ? char.ToUpper(randomLetter()) : randomLetter())
.ToArray());
//string last = makeName(r.Next(7) + 7);
//string company = makeName(r.Next(7) + 7) + " Inc.";
string prodName = makeName(r.Next(5) + 5);
int unitsInStock = r.Next(100);
float unitPrice = (float)(r.NextDouble() * 10);
Product p = new Product();
p.Name = prodName;
p.UnitsInStock = unitsInStock;
p.UnitPrice = unitPrice;
pList.Add(p);
p = null;
}
return pList;
}
When invoked too quickly, multiple
Random r = new Random()‘s will produce Randoms with identical seeds.Declare it once outside the for loop and you should have better values.