Sentry Answers>C#>

How to add values to an array in C#

How to add values to an array in C#

Richard C.

The Problem

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?

Click to Copy
int[] number = new int[2]; number[0] = 1; number[1] = 2; char[] letter = { 'a', 'b' };

How do you add more objects to this List?

Click to Copy
List<string> name = new List<string> { "Alice", "Bob" };

The Solution

First, we need to clarify how arrays and lists work in C#, especially compared to languages like JavaScript, PHP, or Python.

Lists and Arrays are Homogenous

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:

Click to Copy
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.

Lists and Arrays are Different Types

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:

Click to Copy
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.

Add Items to an Array

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:

Click to Copy
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:

Click to Copy
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.

Remove Items From an 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:

Click to Copy
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' } }

Add Items in a Loop

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:

Click to Copy
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' } }

Using Lists Instead of Arrays

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:

Click to Copy
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 } }
  • SentryC# Error and Performance Monitoring
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “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.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.