C# Error CS0255 – stackalloc may not be used in a catch or finally block

C# Compiler Error

CS0255 – stackalloc may not be used in a catch or finally block

Reason for the Error

You’ll receive this error in your C# program when you try to use the stackalloc operator with-in the catch block or finally block.

For example, lets try to compile the below code snippet.

using System;
namespace DeveloperPubNamespace
{
    class Program
    {
        unsafe public static void Main()
        {
            try
            {

            }
            catch(Exception ex)
            {
                // The below statement causes CS0255  
                int* fib = stackalloc int[10];   
            }
        }
    }
}

You will receive the error code CS0255 in your C# program because you are using the stackalloc expression in the catch block of the Main function.

Error CS0255 stackalloc may not be used in a catch or finally block

C# Error CS0255 – stackalloc may not be used in a catch or finally block

Solution

C# Compiler doesnot allow you to use stackalloc operator in the catch or finally block. Avoid using it in the catch block or finally block to fix this error.