If you are like me and have a hard time wrapping your head around arrays in C, let me be your guide. Let’s discuss Arrays in C#.

What are Arrays in C#?

An Array is a way of storing values under the same name and referring to each value using the name plus the index value. The index value starts with ‘0’ for the first value and moves up by 1.

How to Create an Array in C#?

To create an array, name a variable like you normally do, and then place a pair of square brackets “[ ]” right after the variable’s data type. And you have successfully created an array.

To assign value, simply set the variable to a pair of curly brackets “{ }.” Place the values you want to store within these curly brackets, each separated by a comma.

Example of an Array

Here is how you can create an array of cars that will store the brand names of different car companies:

string[] cars = {"Mercedes," "BMW", "Honda", "Porche"};

How to Fetch a Value From an Array in C#?

To fetch a value, use the array’s name, followed by the square brackets and the index of the value you want to fetch.

For example, if you want to fetch BMW, it would be placed at the index “1” because the index value begins from 0.


This will print the following result on the terminal:

Arrays in C#
Arrays in C#

However, to go through the entire array, you must use the Iteration of the array. Which I will cover in a separate blog. Because the main focus of this one was to give a very brief yet clear introduction to arrays in C#.

Also, you can change any value at a specific value by simply referring to the index and setting it equal to something else:

Cars[0] = "Lambo"

This has changed the first element in the array from “Mercedes” to “Lambo”

Before wrapping this up, there are different ways of creating/initializing arrays, which are as follows:

// Create an Empty Place-Holder Array, place the values later
string[] cars = new string[10];

// Declare and Initialize Array in one line
string[] cars = {"Mercedes", "BMW", "Honda", "Porche"};

// Create an Array using the new Keyword, which specifies the size of the array.
string[] cars = new string[] {"Volvo", "BMW", "Ford", "Mazda"};

Well, that sums it all up.

Wrap up

In Summary, Arrays are like cabinets in which you can store multiple objects. To refer to the cabinet, use the name. To refer to the items inside it, use the number of the slot in which there are placed.

If you want to learn about string format in C# visit my blog on C# String Format. Get in touch with this Blog to stay updated with the tutorials on C#.

Categorized in: