C# Array with Examples

What is an array in C#?

What exactly is an array in C#? Variables are used to hold values in programming, but a large number of variables may be needed at once. Writing code in this situation is difficult because each variable must be declared one by one.

Lean more:

If multiple variables of the same data type are needed, arrays can be used for easy coding.

Let's start by looking at sample code that does not require arrays.

  1. using System;
  2. namespace CSharpExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string name1 = "James";
  9. string name2 = "Roland";
  10. string name3 = "Martin";
  11. string name4 = "Mike";
  12. Console.WriteLine(name1);
  13. Console.WriteLine(name2);
  14. Console.WriteLine(name3);
  15. Console.WriteLine(name4);
  16. }
  17. }
  18. }
  19.  

Output:

James
Roland
Martin
Mike

With arrays, you can write like this:

  1. using System;
  2. namespace CSharpExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string[] names = new string[4];
  9. names[0] = "James";
  10. names[1] = "Roland";
  11. names[2] = "Martin";
  12. names[3] = "Mike";
  13. Console.WriteLine(names[0]);
  14. Console.WriteLine(names[1]);
  15. Console.WriteLine(names[2]);
  16. Console.WriteLine(names[3]);
  17. }
  18. }
  19. }

The 8th line is the declaration of an array.

Arrays can contain any number of variables of the same data type.

Array declaration

To declare an array, first describe the data type to be treated like a variable.

Date type[] array_name = new Data type[number_of_elements];

Example:

string[] names = new string[4];

Then use square brackets [].

This indicates that you want to use an array.

Then enter the name of the array to be used.

This name, like the variable name, you can write the name you like.

You have now defined the use of an array, but it has not yet been initialized.

Before arrays can be used, they must be initialized.

To initialize an array, use the new keyword.

Then define the same data type as before and write the size of the array as a number in [].

Array size (number of elements)

The size of an array is the number of data that can be stored in it.

It is also called the number of elements.

An element is a piece of data that is stored in an array.

The array in the sample code can store three int types of data.

Access to array elements

To assign a value to or retrieve a value from each element of an array, specify the element you wish to access as a number using square brackets [].

The subscript operator is the name (indexer) of these square brackets.

The subscript, index, is the number described by the subscript operator.

Array subscripts start with "0".

So if you declare the use of an array with four elements, the subscripts for each element would be "0", "1", "2", and "3".

It is worth noting that the last element number of the array is one less than the total number of elements.

It can then be used as a variable.

A variable is the same as taking a value and assigning it.

Example:

  1. string[] names = new string[4];
  2. names[0] = "James";
  3. names[1] = "Roland";
  4. names[2] = "Martin";
  5. names[3] = "Mike";
  6. Console.WriteLine(names[0]);
  7. Console.WriteLine(names[1]);
  8. Console.WriteLine(names[2]);
  9. Console.WriteLine(names[3]);

Array initialization

While the previous initialization method simply specifies the number of array elements, there are other convenient initialization methods.

Stores a value in each element at the same time as initialization

string names = new string[4] { "James", "Roland", "Martin", "Mike" };

As soon as the array "names" is declared, the values "James", "Roland", "Martin", and "Mike" are stored, starting with the first element.

The initialization list (braces) is also called the array initializer.

In the sample code above, the array was automatically initialized with default values because no initializer list was provided.

"null" is the default value for string data types.

Omission of number of elements

When initializing using an initialization list, the specification of the number of array elements can be omitted.

  1. string[] words = new string[]
  2. {
  3. "Word 1", "Word 2", "Word3", "Word 4"
  4. };
  5. int[] numbers = new int[] { 2, 3, 4, 5, 6, 5 };

The size of the array is automatically determined by the number of data in the initialization list.

When specifying the number of array elements in the array initialization declaration, the number of elements and the number of data in the initialization list must be the same, or an error will result.

In other words, if the number of elements in the initialization list is changed, the number of data in the initialization list must be changed as well.

In many cases, the number of elements is not specified because it is inconvenient.

Omission of data type

When using an initialization list when declaring an array, the data type specification after the new keyword can be omitted.

  1. string[] words = new []
  2. {
  3. "Word 1", "Word 2", "Word3", "Word 4"
  4. };
  5. int[] numbers = new [] { 2, 3, 4, 5, 6, 5 };

Omission of new

When using an initialization list when declaring an array, it is possible to omit the "new" keyword and data types.

  1. string[] words =
  2. {
  3. "Word 1", "Word 2", "Word3", "Word 4"
  4. };
  5. int[] numbers = { 2, 3, 4, 5, 6, 5 };

The initialization list can only be used at initialization.

Setting values to an array using an initialization list can only be used when the array is initialized.

  1. int[] numbers = new int[2];
  2. //Error
  3. numbers = { 10, 30};
  4. //OK
  5. numbers = new int[2] { 10, 30 };

Out of range access

Specifying a value greater than or equal to the array size or a negative value for the array subscript will result in an error.

  1. //Minus cannot be specified
  2. words[-1] = "Word 5";
  3. //Index is too large
  4. words[4] = "Word 6";

This error cannot be detected at the time the code is written (compiled) but becomes a runtime error.

Since it is not a grammatical error, you will not know if it is an error until you actually run the program.

Getting the size of an array

Use the Length property to find the size of an array.

  1. using System;
  2. namespace CSharpExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string[] words = new[]
  9. {
  10. "Word 1", "Word 2", "Word3", "Word 4", "Word 5"
  11. };
  12. int size = words.Length;
  13. Console.WriteLine("Array size: {0}", size);
  14. }
  15. }
  16. }

Output:

Array size: 5

Copying an entire array

Each element of an array can be treated as an ordinary variable, but the array itself, i.e., without subscripts, is treated somewhat differently.

For example, if you want to copy an entire array, try assigning another array variable to the array variable, as shown below:

  1. using System;
  2. namespace CSharpExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string[] words = new[]
  9. {
  10. "Word 1", "Word 2", "Word 3", "Word 4", "Word 5"
  11. };
  12.  
  13. string[] words2 = words;
  14. for (int i = 0; i < words2.Length; i++)
  15. {
  16. Console.WriteLine(words2[i]);
  17. }
  18. }
  19. }
  20. }

Output:

Word 1
Word 2
Word 3
Word 4
Word 5

At first glance, it looks like it's working.

In the array "words2" of this code, the values of each element of the array "words" are not copied, and it becomes the array "words" itself.

Let's try rewriting the value of the source array words.

After assigning words to words2, no changes are made to words2.

If you then rewrite the value of words[1], you will see that the value of words2[1] has also changed.

  1. using System;
  2. namespace CSharpExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string[] words = new[]
  9. {
  10. "Word 1", "Word 2", "Word 3", "Word 4", "Word 5"
  11. };
  12.  
  13. string[] words2 = words;
  14. words[1] = "Word 6";
  15. for (int i = 0; i < words2.Length; i++)
  16. {
  17. Console.WriteLine(words2[i]);
  18. }
  19. }
  20. }
  21. }

Output:

Word 1
Word 6
Word 3
Word 4
Word 5

In other words, when you assign another array to an array, it is not a copy of each element, but an alias of the array to which it was assigned.

If you want a copy of each element, this method will not work.

Copying the entire contents of an element

If you want to copy an entire element, the simplest way is to assign each element one by one.

  1. using System;
  2. namespace CSharpExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string[] words = new[]
  9. {
  10. "Word 1", "Word 2", "Word 3", "Word 4", "Word 5"
  11. };
  12.  
  13. string[] words2 = new string[words.Length];
  14. for (int i = 0; i < words.Length; i++)
  15. {
  16. words2[i] = words[i];
  17. }
  18. words[1] = "Word 6";
  19. //Print the elements of words
  20. Console.WriteLine("The elements of words:");
  21. for (int i = 0; i < words.Length; i++)
  22. {
  23. Console.WriteLine(words[i]);
  24. }
  25. //Print the elements of words2
  26. Console.WriteLine("The elements of words2:");
  27. for (int i = 0; i < words2.Length; i++)
  28. {
  29. Console.WriteLine(words2[i]);
  30. }
  31. }
  32. }
  33. }

Output:

The elements of words:
Word 1
Word 6
Word 3
Word 4
Word 5
The elements of words2:
Word 1
Word 2
Word 3
Word 4
Word 5

It is difficult with a large number of elements, but it can be easily written using a loop statement such as a for statement.

There are other ways to use the built-in function.

  1. using System;
  2. namespace CSharpExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string[] words = new[]
  9. {
  10. "Word 1", "Word 2", "Word 3", "Word 4", "Word 5"
  11. };
  12.  
  13. string[] words2 = new string[words.Length];
  14. //Copy an array
  15. Array.Copy(words, words2, words2.Length);
  16. //
  17. words[3] = "Word 7";
  18. //Print the elements of words
  19. Console.WriteLine("The elements of words:");
  20. for (int i = 0; i < words.Length; i++)
  21. {
  22. Console.WriteLine(words[i]);
  23. }
  24. //Print the elements of words2
  25. Console.WriteLine("The elements of words2:");
  26. for (int i = 0; i < words2.Length; i++)
  27. {
  28. Console.WriteLine(words2[i]);
  29. }
  30. }
  31. }
  32. }

You can see that rewriting the elements of words does not affect words2.

This is because words2 is now an array independent of words.

You can also use the Linq as the following sample program shows:

  1. using System;
  2. using System.Linq;
  3. namespace CSharpExample
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. string[] words = new[]
  10. {
  11. "Word 1", "Word 2", "Word 3", "Word 4", "Word 5"
  12. };
  13. //Copy an array
  14. string[] words2 = words.ToArray();
  15. //
  16. words[4] = "Word 8";
  17. //Print the elements of words
  18. Console.WriteLine("The elements of words:");
  19. for (int i = 0; i < words.Length; i++)
  20. {
  21. Console.WriteLine(words[i]);
  22. }
  23. //Print the elements of words2
  24. Console.WriteLine("The elements of words2:");
  25. for (int i = 0; i < words2.Length; i++)
  26. {
  27. Console.WriteLine(words2[i]);
  28. }
  29. }
  30. }
  31. }

Output:

The elements of words:
Word 1
Word 2
Word 3
Word 4
Word 8
The elements of words2:
Word 1
Word 2
Word 3
Word 4
Word 5

Summary

In this tutorial, you learned what C# arrays are and how to use them.


See also:
C# List Contains with Examples
C# typeof with Examples
C# TryParse (int, double, float) with Examples
C# Data Types
C# Variables