DEV Community

Cover image for How to Make an Array in C# for Beginners
Emmanuel Pangan
Emmanuel Pangan

Posted on • Updated on

How to Make an Array in C# for Beginners


Watch the full video on YouTube.

Hello aspiring developers! πŸ‘¨β€πŸ’» So you're probably wondering how can you sort this variable mess, after maybe 10 or more added:

// Variables like this becomes messy.
string student1 = "John";
string student2 = "Michael";
string student3 = "Petra";
Enter fullscreen mode Exit fullscreen mode

Here's how:

Just add the type and square brackets beside. Name it. Then put new and the type, then add its length inside these brackets.

// To solve this, you can make an array.
string[] students = new string[3];
Enter fullscreen mode Exit fullscreen mode

And what is length you ask?
Length - total number of items you can put inside array.

And you can initialize this by adding each value based on index.

// To solve this, you can make an array.
string[] students = new string[3];
students[0] = "John";
students[1] = "Michael";
students[2] = "Petra";
Enter fullscreen mode Exit fullscreen mode

Or, you can also initialize this in one go, by undoing the initialize values before. And remove the new, the type, and the length to not worry on how many values you will put inside.

Add a pair of curly braces, then put the values inside, each separated by a comma. Here you go! Much compact code using arrays. πŸ˜‰

// To solve this, you can make an array.
string[] students = { "John", "Michael", "Petra" };
Enter fullscreen mode Exit fullscreen mode

Calling a value in an Array

To call a value inside an array, we can use their index. Starting from 0 β€˜til the array’s length minus one.

Console.WriteLine("Student Name: " + students[students.Length - 1]); 
Enter fullscreen mode Exit fullscreen mode

Array's Index - always start from 0 and not 1.

students[students.Length - 1] - is the same as: students[3 - 1]

You can also use other types aside from string.

Like int:

// You can also use other types aside from string.
int[] ages = new int[3];
ages[0] = 12;
ages[1] = 17;
ages[2] = 24;
Enter fullscreen mode Exit fullscreen mode

And double:

double[] grades = new double[3];
grades[0] = 75.0;
grades[1] = 80.5;
grades[2] = 97.1;
Enter fullscreen mode Exit fullscreen mode

Here's the final code you can view on GitHub Gist.

Thanks for reading! πŸ“–

Check out my YouTube channel for more coding tutorials. Happy coding everyone! 🧑

Source(s):
Microsoft's documentation on C# Arrays

Top comments (0)