C# OutOfMemoryException

Warning

You are pondering the OutOfMemoryException type in the C# language and .NET Framework, and are interested in how this exception is thrown. The OutOfMemoryException is triggered by allocation instructions and is thrown by the execution engine; it can occur during any allocation call during runtime, and there are ways to predict the failure.

This C# exception article demonstrates OutOfMemoryException.

Example

In this example, we see a program that attempts to allocate a string that is extremely large and would occupy four gigabytes of memory. However, the OutOfMemoryException is thrown by the runtime because this is not possible. The intention of the program is to demonstrate the exception itself and not to provide a realistic example. After the program, we note ways to deal with the exception in the .NET Framework.

Program that raises out-of-memory exception [C#]

class Program
{
    static void Main()
    {
	// This program attempts to create a string of 2.1 billion characters.
	// ... This results in an out-of-memory error.
	// ... It would require 4.2 billion bytes (4 gigabytes).
	string value = new string('a', int.MaxValue);
    }
}

Output

Unhandled Exception: OutOfMemoryException.
Question and answer

How much memory can be counted on? 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 the MemoryFailPoint type to help diagnose the issue. Please see the note on MemoryFailPoint below.

Intermediate language instructions. The MSDN documentation notes that 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.

MSDN referenceProgramming tip

MemoryFailPoint. The OutOfMemoryException can sometimes 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 and this is useful for cases when you have a critical computation and will require a lot of memory and do not want any failures during the method. The book CLR via C# by Jeffrey Richter contains a good explanation of the MemoryFailPoint type.

Summary

.NET Framework information

We saw a contrived program written in the C# language 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 on any program, and it is hard to predict when this may occur, although practically it happens rarely in most programs and systems with typical resources. Finally, we noted that there exists a way to predict the OutOfMemoryException in the .NET Framework.

Exception Handling
.NET