C# OutOfMemoryException
Program.cs
int size = int.MaxValue;
Console.WriteLine(size);
string[] s = new string[size];
Output
kodingwindow@kw:~/csharp$ dotnet run
2147483647
Out of memory.
kodingwindow@kw:~/csharp$ 
C# OutOfMemoryException
Program.cs
using System;
namespace Kodingwindow
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Stack<int> st = new Stack<int>(int.MaxValue);
        }
    }
}
Output
kodingwindow@kw:~/csharp$ dotnet run
Out of memory.
kodingwindow@kw:~/csharp$ 
C# program to handle the OutOfMemoryException
Program.cs
int size = int.MaxValue;
try
{
    string[] s = new string[size];
}
catch (OutOfMemoryException e)
{
    Console.WriteLine("Array overflow");
    Console.WriteLine(e.Message);
}
Output
kodingwindow@kw:~/csharp$ dotnet run
Array overflow
Array dimensions exceeded supported range.
kodingwindow@kw:~/csharp$ 
Advertisement