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
Solution
You can fix this error in C# by ensuring you always pass a positive integer number to the stackalloc expression.