Home >Backend Development >C++ >How Can I Add Values to a C# Array?

How Can I Add Values to a C# Array?

Susan Sarandon
Susan SarandonOriginal
2025-01-19 17:42:12233browse

How Can I Add Values to a C# Array?

Add value to C# array

When initializing an array in C#, you may need to fill it with values. Unlike PHP (which can dynamically expand arrays using array[]), adding elements to a C# array requires a different approach due to the strongly typed nature of the C# language.

The following methods can be used to add values ​​to C# arrays:

<code class="language-csharp">int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++) {
    terms[runs] = runs; // 将值赋给数组的每个元素
}</code>

This example first creates an array called "terms" containing 400 integers. The "for" loop then iterates through each index of the array and assigns the value "runs" (the loop counter) to each element. Unlike PHP, C# does not support direct expansion of arrays, and the array size must be specified at creation time.

Alternatively, you can use List, which provides dynamic resizing:

<code class="language-csharp">List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++) {
    termsList.Add(runs); // 使用Add()方法添加元素
}</code>

List Provides a flexible approach to data management without specifying an initial size. However, it's important to note that arrays generally perform better than List, especially with indexing and looping.

The above is the detailed content of How Can I Add Values to a C# Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn