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

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

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...