Tjh Thon
Tjh Thon

Reputation: 85

Can't see any resources referring to static arrays in C#

Arrays in C#, including n-dimensional arrays and jagged ones, are all declared using new operator. Does it mean that C# only utilizes dynamic arrays?

P.S: by saying dynamic arrays, I mean arrays which are dynamically allocated, with their values in the heap and pointer referring to them in the stack.

Upvotes: 0

Views: 25

Answers (2)

Eric Damtoft
Eric Damtoft

Reputation: 1423

Arrays in c# are fixed size (I assume that by dynamic you mean dynamically resizeable). To create a "dynamic" collection, you could use List<T>. Under the covers, List<T> is backed by an array which is re-allocated and copied as the list grows.

The new operator is used because it represents that the runtime is allocating space for an object, in this case an Array object. The new keyword is used for anything which is not a compile-time constant (I.E. a hardcoded number, boolean, or string).

Upvotes: 0

adjan
adjan

Reputation: 13652

Yes, arrays in C# are usually dynamically allocated on the heap. All array types inherit from System.Array, which is a reference type.

Though, arrays can be allocated on the stack using the stackalloc keyword, which requires an unsafe context and is usually used for interoperability with native APIs etc.

Upvotes: 2

Related Questions