Trending September 2023 # How Outofmemoryexception Works In C#? # Suggested October 2023 # Top 12 Popular |

Trending September 2023 # How Outofmemoryexception Works In C#? # Suggested October 2023 # Top 12 Popular

You are reading the article How Outofmemoryexception Works In C#? updated in September 2023 on the website We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested October 2023 How Outofmemoryexception Works In C#?

Introduction to C# OutOfMemoryException

OutOfMemoryException in C# is an exception that is thrown by the .NET framework execution engine when the program does not have enough memory to continue its execution. As its name suggests this exception will occur in our program when the CLR i.e. Common Language Runtime will not be able to allocate enough memory which will be required to perform certain operations of our program.

Start Your Free Software Development Course

This exception does not always mean that we do not have enough space available in memory but sometimes it means that we do not have enough contiguous memory which is required by our program for allocation.


The syntax to catch an OutOfMemoryException in C# is as follows:

try { } catch(OutOfMemoryException exception) { }

The syntax to throw an OutOfMemoryException in C# is as follows:

throw new OutOfMemoryException();

In the above statement ‘throw’ is the keyword which is used to throw exceptions in C#.

How OutOfMemoryException works in C#?

In C#, we get OutOfMemoryException when our program does not have enough space to continue its execution. There could be many reasons for getting this exception. We also encounter this exception when in total we have enough space for our program to execute but this space is not contiguous for the allocations required to be done by our program. The two major reasons for this exception are as follows:

Trying to increase the length of a StringBuilder object beyond the length which is specified by the MaxCapacity property of StringBuilder.

We will get the exception saying “Insufficient memory to continue the execution of the program.”

When we are making an assignment or calling a method that requires memory allocation and at the same time the CLR is not able to provide enough contiguous memory for our allocation then we will get OutOfMemoryException.

The other reasons which can become the cause of this exception include:

Running the application on a 32-bit system which has only 2GB of virtual memory due to which CLR finds it difficult to provide contiguous memory for the allocations required by the application.

Working with large data sets requires a huge amount of memory and if CLR does not have enough contiguous space available for it then it results in OutOfMemoryException.

As strings are immutable, the operations performed on string create a new string in the memory. So if we are working with large strings and if we are performing concatenation operation repeatedly on the string then it can lead to multiple memory allocations which in result will degrade the performance of our application and can become a cause of OutOfMemoryException.

If we have pinned multiple objects in the memory for a very long period then it becomes difficult for the garbage collector to provide contiguous memory allocation to these objects.


Here are the following examples mention below

Example #1

Example showing OutOfMemoryException thrown by the program when we try to expand the StringBuilder object beyond its maximum capacity.


using System; using System.Text; public class Program { public static void Main() { StringBuilder stringBuilder = new StringBuilder(17, 17); stringBuilder.Append("Welcome to the "); try { stringBuilder.Insert(0, "world of C# programming", 1); Console.WriteLine(stringBuilder.ToString()); Console.ReadLine(); } catch (OutOfMemoryException exception) { Console.WriteLine(exception.Message); Console.ReadLine(); } } }


Example #2

Example showing a program that encounters OutOfMemoryException while trying to add the element in the list where the number of elements to be added is more than the capacity of the list.

using System; using System.Text; using System.Collections.Generic; namespace ConsoleApp4 { public class Program { public static void Main() { try { string[] strArray = GetArray(); Console.WriteLine(strArray); Console.ReadLine(); } catch (OutOfMemoryException exception) { Console.WriteLine(exception); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } } public static string[] GetArray() { for (int i = 0; i <= int.MaxValue; i++) { strList.Add("Hello"); } return strList.ToArray(); } } }


How to avoid OutOfMemoryException in C#?

We can avoid OutOfMemoryException in C# by keeping in mind the following points:

To avoid this exception while working with StringBuilder, we can call the constructor StringBuilder.StringBuilder(Int32, Int32) and can set the MaxCapacity property to a value that will be large enough to serve the accommodation required when we expand the corresponding StringBuilder object.

To avoid this exception while working on a 32-bit system, we can recompile our application from 32 bit to 64-bit system in visual studio by below steps:

If the 64-bit platform is not available in the list then:

To avoid getting this exception while working with unmanaged resources, we should always call Dispose() method after completing our work with the unmanaged resource which is no longer required.

To avoid this exception while working with large data sets, we should try to filter the data and then should pass only the required data for processing.

To avoid this exception while working with large strings or while performing large string concatenation, we can make use of StringBuilder instead of string because StringBuilder is mutable and does not create a new instance of the string when we perform any operation on it.


The OutOfMemoryException is a runtime exception that tells the programmer that there is no enough memory or there is a lack of contiguous memory for the allocations required by the C# program.

To avoid this exception the user should always take necessary precautions and should handle this exception.

Recommended Articles

This is a guide to C# OutOfMemoryException. Here we discuss how OutOfMemoryException works in C# along with the programming examples. You may also have a look at the following articles to learn more –

You're reading How Outofmemoryexception Works In C#?

Update the detailed information about How Outofmemoryexception Works In C#? on the website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!