[C #] Exception out of memory

Heitor Helmer Herzog
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);
}

--

--

Heitor Helmer Herzog
Heitor Helmer Herzog

Written by Heitor Helmer Herzog

Software developer, In love with games and the industry. Let’s code! About me: www.linkedin.com/in/heitorhherzog

No responses yet