C# OutOfMemoryExceptionUnderstand the OutOfMemoryException, which occurs when not enough memory is available.
Memory is limited. The OutOfMemoryException is triggered by allocation instructions. It is thrown by the .NET Framework execution engine. It can occur during any allocation call during runtime.Exception
In this example,
we see a program that attempts to allocate a string that is extremely large and would occupy four gigabytes of memory. But the OutOfMemoryException is thrown by the runtime because this is not possible.
Note: The intention of the program is to demonstrate the exception itself. After the program, we note ways to deal with the exception.
C# program that raises out-of-memory exception
static void Main()
// Attempt to create a string of 2.1 billion chars.
// ... This results in an out-of-memory error.
// ... It would require 4.2 billion bytes (4 gigabytes).
string value = new string('a', int.MaxValue);
Unhandled Exception: OutOfMemoryException.
How much memory can be assumed?
No specific amount of memory in bytes can be counted on when executing a program. For most programs that do not allocate huge amounts of memory, this is not a serious problem.
However: If you have a problem with this exception and the cause is not obvious, you can use MemoryFailPoint to help diagnose the issue.
There are three
IL instructions that can raise this exception: the box, newarr, and newobj instructions. These are used when converting a value type to an object type, and for allocating arrays and classes.OutOfMemoryException: Microsoft DocsIL: newarr
The OutOfMemoryException may be predicted in advance with special code that uses the MemoryFailPoint class in the .NET Framework. This type will indicate if the memory can be allocated.
Tip: This is useful when you have a critical computation and will require a lot of memory and want no failures during the method.
Note: The book CLR via C# by Jeffrey Richter explains the MemoryFailPoint type.
We saw a program that attempts to allocate a 4-gigabyte block of memory, but this fails and throws the OutOfMemoryException. This exception can be thrown during any allocation instruction. It is hard to predict when this may occur.
But: It happens rarely in most well-designed programs and systems with typical resources.
Finally: We noted that there exists a way to predict the OutOfMemoryException in the .NET Framework.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.