-6

I am trying to understand why I am able to create a C# array without specifying the size at compile time.

C# documentation mentions that you declare an array by specifying its size. In most array initialization examples, I see int[] myArray = new int[5];

Yet, in my example, the size is determined at runtime when the function is invoked. I understand that a List is recommended when the size is not known.

However, for the sake of learning, I would like to get feedback on why this works. Im currently on NET 9.0.200

I have already reviewed the below questions, but none provide detail on why this is possible.

Array of an unknown length in C#

Making an array of an unknown size C#

C# Array without a specified size

public int[] CreateArray(int size) 
{
    int[] numbers = new int[size];

    for (int i=0; i<size; i++)
    {
        numbers[i] = i;
    }

    return numbers;
}

4
  • 8
    Why do you think array size needs to be known at compile time, in the first place? Commented Apr 3 at 21:47
  • 3
    Arrays are dynamically allocated. Commented Apr 3 at 21:57
  • 3
    Unlike a language like C, in C# arrays are created at run-time, not compile-time. So using a variable to specify the size is not special. The C-style of arrays exist in C# as well Commented Apr 3 at 22:04
  • 1
    why do you think you need to use lists for data of unknown size, when your example proves exactly the opposite? Why should an array be compile-time fixed? Usually the answer to this kind of question is: "because the developers of the language designed it so, because they found it useful" - which in case of a dynamically sized array most C#-developers would agree with. Commented Apr 4 at 5:26

1 Answer 1

6

You're still initializing an array with a fixed size. You may not know the size at compile time, but you'll know it at runtime and that's good enough. The size of an array needs to be an int, not necessarily a hard-coded int.

If, however, you also don't know the size of a collection at runtime, a very common case, you use List<T>.

In most cases, you'll encounter situations where you won't know the size of a collection at compile time and not even at runtime.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.