Home >Backend Development >C++ >How to Add Items to a C# Array?
Extending C# Arrays: A Practical Guide
C# arrays, unlike some languages, aren't directly extensible. This means you can't simply add elements to a pre-defined array. However, several methods efficiently handle adding new items while preserving existing data.
Leveraging the Power of Lists
The most common and efficient approach involves using a List<T>
, a dynamic array that automatically adjusts its size. Here's how to add items to an existing string array:
<code class="language-csharp">List<string> newList = new List<string>(existingArray); newList.Add("New Item"); string[] newArray = newList.ToArray();</code>
This code snippet first converts the existingArray
into a List<string>
. The new item is then appended. Finally, the List<string>
is converted back into a string[]
array, newArray
, containing all the original elements plus the addition. This method maintains data integrity and provides flexibility.
The above is the detailed content of How to Add Items to a C# Array?. For more information, please follow other related articles on the PHP Chinese website!