'I can't display member of List in c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kelime_Türet
{
class Program
{
static void Main(string[] args)
{
List<string> Words = new List<string>();
for (int i = 0; i < 5; i++)
{
string word = CreateWord();
Words.Add(word);
}
foreach (var item in Words)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
static string CreateWord()
{
string Word = "";
string Letters = "qwertyuıopğüişlkjhgfdsazxcvbnmöç";
Random r = new Random();
for (int i = 0; i < 10; i++)
{
int index = r.Next(0, 32);
Word += Letters[index];
}
return Word;
}
}
}
I'm able to display same member of the List, I can't display all member via foreach loop. I'm sure that i have added items to the List but i can't display them. I can see List content when i use breakpoint. The problem is when i try to display all members of the List, i only can display same member.
Solution 1:[1]
The problem is in the new Random(). Each time you create Random it's initialized by system timer value.
If you routine is fast enough, you have all Random r having same seed and that's why generating same values.
// Don't create local Random instances, keep just one static field instead
static Random r = new Random();
static string CreateWord()
{
// Don't create local Random instances here, use static Random
string Word = "";
string Letters = "qwertyu?op?üi?lkjhgfdsazxcvbnmöç";
for (int i = 0; i < 10; i++)
{
int index = r.Next(0, 32);
Word += Letters[index];
}
return Word;
}
Fiddle yourself
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dmitry Bychenko |
