C# Error CS0248 – Cannot create an array with a negative size

C# Compiler Error

CS0248 – Cannot create an array with a negative size

Reason for the Error

You will receive this error in C# when you are trying to create an array with a negative number being specified to it.

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

namespace DeveloperPubNamespace
{
   class Program
    {

        public static void Main()
        {
            unsafe
            {
                int[] array1 = new int[-15];
            }
        }
    }
}

You will receive the error code CS0248 in your C# program because you are trying to create an array of integer by specifying the size of the array to be -15. This is invalid in the context of array and hence C# identifies this as error.

Error CS0248 Cannot create an array with a negative size DeveloperPublish C:\Users\SenthilBalu\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 10 Active

C# Error CS0248 – Cannot create an array with a negative size

Solution

The array size in C# should always be a positive number. To fix the error code CS0248, ensure that you always pass a positive number when creating an array.

namespace DeveloperPubNamespace
{
   class Program
    {

        public static void Main()
        {
            
            {
                int[] array1 = new int[15];
            }
        }
    }
}

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...