C# Error CS0247 – Cannot use a negative size with stackalloc

C# Compiler Error

CS0247 – Cannot use a negative size with stackalloc

Reason for the Error

The stackalloc expression in C# is used to allocate a block of memory on the stack data structure. You can easily define a stackalloc expression as shown below.

namespace DeveloperPubNamespace
{
   class Program
    {

        public static void Main()
        {
            unsafe
            {
                int* pointer = stackalloc int[10];  
            }
        }
    }
}

You will receive the error code CS0247 when you are passing a negative value to the stackalloc expression as shown below.

For example, try compiling the below code snippet.

namespace DeveloperPubNamespace
{
   class Program
    {

        public static void Main()
        {
            unsafe
            {
                int* pointer = stackalloc int[-5];  
            }
        }
    }
}

Error CS0247 Cannot use a negative size with stackalloc DeveloperPublish C:\Users\SenthilBalu\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 10 Active

C# Error CS0247 – Cannot use a negative size with stackalloc

Solution

You can fix this error in C# by ensuring you always pass a positive integer number to the stackalloc expression.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...