[C #] Exception out of memory
1 min readJul 8, 2017
When we need to deal with a large amount of objects and put them in some list we may have some problems, in addition to memory consumption we can also come up against with the exception of out of memory.
Let’s look at the example below:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Create a list of 10000000000
var l1 = Enumerable.Range(0, 1000000000).ToList();
// displays each item in the console
l1.ForEach(f => Console.WriteLine(f));
}
}
}
To solve the problem of having to insert 10000000000 objects
in the memory
We can use another approach.
Create a method that returns the type IEnumerable
And return the type by passing the word yield
IEnumerable GetNextInt()
{
for(int i=999900000; i< 1000000000; i++)
{
yield return i;
}
}
With this instead of returning all the objects and storing
in the memory
The method returns one item at a time
foreach(var integer in GetNextInt())
{
Console.WriteLine(integer);
}