Assuming numToGenerate
, min
, and max
are the same for both snippets and GetNextRandom
is a method that uses an instance of System.Random
to generate a random integer by simply returning the value of instance.Next(min, max)
.
First snippet using yield:
var list = new List<int>();
while(list.Count < numToGenerate)
{
var next = GetNextRandom(min, max);
if (!list.Contains(next))
{
list.Add(next);
yield return next;
}
}
Second snippet using normal return:
var list = new List<int>();
while(list.Count < numToGenerate)
{
var next = GetNextRandom(min, max);
if (!list.Contains(next))
{
list.Add(next);
}
}
return list;
Let's pretend these snippets are part of a method that returns IEnumerable<int>
. What are the major differences of the two? Which should I be using and why? I'm trying to understand the functional difference if any.