Richard C.
—If you have an array of items in C#, like a list of people or numbers, how do you add more items to the list?
For example, how do you add more numbers or letters to these two arrays?
int[] number = new int[2]; number[0] = 1; number[1] = 2; char[] letter = { 'a', 'b' };
How do you add more objects to this List
?
List<string> name = new List<string> { "Alice", "Bob" };
First, we need to clarify how arrays and lists work in C#, especially compared to languages like JavaScript, PHP, or Python.
In C#, collections like a List
and an array can contain only elements of the same type. In Python you can create a heterogeneous list:
items = [1, "two", 3.0, {"four": 4}, [5, "six"]]
However, in C# this is not allowed. You would have to store either numbers or strings or objects with both properties that you define in a custom class.
In interpreted languages, there is no difference between a list and an array. For instance, an array and a list are the same in JavaScript. You can add items at any time:
let items = ['1', '2', 3]; items.push("four");
In compiled languages like C#, where memory use is more important, arrays and lists are separate things. Arrays have a fixed length, which you specify when declaring the variable. This saves space in RAM and runs faster. Lists are complex objects, with pointers to items kept in different places in RAM, that can grow and shrink whenever you want.
Say you have an array of numbers, which you know is of a fixed length. But you still want to add items (increasing the length of the array), or remove items (and then remove the empty elements to shorten the length of the array). It’s possible — but you cannot alter the original array. You have to instead replace it with a new array. Here’s how:
using System; using System.Linq; public class Program { public static void Main() { char[] letter = ['a', 'b']; letter = letter.Append('c').ToArray(); letter = letter.Concat(['d', 'e']).ToArray(); Console.WriteLine(letter); // 'abcde' } }
This code uses .NET 8. If you’re using an older version of .NET you create arrays with new
and curly braces, instead of square brackets:
char[] letter = new char[] { 'a', 'b' };
How do Concat
and Append
work? They use LINQ to create a list(IEnumerable<char>
) for your original letter
array, where mutation of the length is allowed. They then add a char, or list of chars, to the original array, and then return the result as a new array. This array overwrites the original array. So you haven’t “added” an item to the array so much as replaced the variable with a new array.
You can also use LINQ to convert the array to a list, remove elements, and convert it back to an array to overwrite the variable:
using System; using System.Linq; public class Program { public static void Main() { char[] letter = ['a', 'b']; letter = letter.Take(1).ToArray(); Console.WriteLine(letter); // 'a' } }
If you haven’t yet filled an array, you can populate it easily using a loop, without having to alter its length. Here’s an example where we add the first 10 letters of the alphabet to a new empty array:
using System; public class Program { public static void Main() { var letters = new char[10]; for (int i = 0; i < letters.Length; i++) letters[i] = (char)('a' + i); Console.WriteLine(letters); // 'abcdefghij' } }
Since items in an array have fixed locations in memory, it’s very fast for the CPU to alter them. But if you are frequently changing the length of an array, .NET has to copy the entire array to a new array every time. This will reduce the speed of your application when working with large arrays. In this case, it’s better to use a List
. Lists take more space in memory than arrays but are much faster to work with when changing size.
Here’s an example of how to create a list, and add and remove items:
using System; using System.Collections.Generic; public class Program { public static void Main() { var letter = new List<char> { 'a', 'b' }; letter.Add('c'); letter.Add('d'); letter.Remove('c'); Console.WriteLine(String.Join(", ", letter)); // a, b, d } }
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.