Unlike PHP's dynamic array handling, C# arrays require a predefined size. Let's illustrate this difference with an example.
PHP's approach is straightforward:
<code class="language-php">$arr = array(); for ($i = 0; $i < 5; $i++) { $arr[] = $i; }</code>
This PHP code creates an empty array and adds elements using the []
syntax. C#, however, needs a different approach.
To add values to a C# array, you must declare its size beforehand. Here's the C# equivalent of the PHP example:
<code class="language-csharp">int[] terms = new int[5]; for (int runs = 0; runs < 5; runs++) { terms[runs] = runs; }</code>
This code creates an integer array terms
with a capacity of 5 elements. The []
syntax is then used to assign values.
A more flexible alternative in C# is the List<T>
collection. Lists dynamically resize, allowing you to add elements without predefining the size:
<code class="language-csharp">List<int> termsList = new List<int>(); for (int runs = 0; runs < 5; runs++) { termsList.Add(runs); }</code>
Choosing between arrays and lists depends on your needs. Arrays are generally faster for accessing elements and have better memory management, while lists offer greater flexibility and ease of use for dynamic data.
The above is the detailed content of How Do I Add Values to Arrays in C#?. For more information, please follow other related articles on the PHP Chinese website!