System ProgrammingLearn about Arrays in C# Programming

Learn about Arrays in C# Programming

Welcome to Arrays, an interesting topic that you will like. So, enjoy!

An array is a collection of data elements that are stored together and belong to the same data type. So, arrays are used to store multiple variables of the same type. An array can contain a number of enums, structs, strings, integers or any other data type, as long as they are of the same type.

You’ll find yourself in need for using arrays many times because of the power they provide. In all of the previous article’s examples, we have examined how we can store student properties in a struct, or one of the student properties (grades) in a user-defined data type (enum). But what if you want to store a group of students? Consider the following example:

enum grades
{
    Excellent,
    Good,
    Fair
}

struct student {
    public string firstname;
    public string lastname;
    public int age;
}
student student1;
student student2;
student student3;

student1.firstname = "Sara";
student1.lastname = "Longman";
student1.age = 20;
student1.stGrade = grades.Excellent;

student2.firstname = "Ahmed";
student2.lastname = "Fahmy";
student2.age = 19;
student2.stGrade = grades.Good;

student3.firstname = "Mohamed";
student3.lastname = "Fathy";
student3.age = 21;
student3.stGrade = grades.Fair

static void Main(string[] args)
{
	student[] arrStudents = {student1, student2, student3};

}

The only new thing in this code sample should be the last line where you defined the array. Notice the square brackets that followed the array type (student). This is mandatory Arrays can be defined either this way (adding the items separated by a comma), or by specifying the size of the array and then adding the items later. Let’s replace the last line of the last example with this:

student[] arrStudents = new student[2];

Here we initialized an empty array using the new keyword. If you want to initialize an empty array, you must define its size. Our array can hold 3 students. But we mentioned 2 in the array size is that a typo? No, arrays use zero based placement. This means that the first item in an array will have an index of 0, the second one 1 and so on. So the size of a given array can be obtained by subtracting 1 from the N number of items it contains (N – 1). But now the array is empty, we want to add our students. Let’s do that:

student[] arrStudents = new student[2];
arrStudents[0] = student1;
arrStudents[1] = student2;
arrStudents[2] = student3;

NOTICE
The previous example is only for demonstrating the difference between an enum, a struct, and an array. Do not run it in the main function as the compiler will complain because you are running code that contains non static objects in a static function. Do not bother yourself now with these term, we’ll cover them later in this course. Just get the idea for now.

You can work with arrays using their indexes; either setting or getting the value of the item(s).

If you want to display all the items of an array use loops. A for loop is useful here provided that you’ll always know the size of the array. Consider this example:

string[] myArray = {"This","is","an","example"};
for (int i = 0; i < 4; i++)
{
    Console.WriteLine(myArray[i]);
}

If you run this code in your main function, the output will be as follows:

“This”
“is”
“an”
“example”

You used a for loop where you assigned an integer i  the value of 0, which is the index of the first item in the array of strings you defined. Then the loop is cycling through the array by adding 1 to i as long as it is less than 4 (the largest index + 1).

Learn Cloud Computing from Scratch for Beginners

Accessing arrays using the foreach loop
You can work with the students array we created in the last article using this method:

class MainClass
    {
        enum grades
        {
            Excellent,
            Good,
            Fair
        }

        struct student {
            public string firstname;
            public string lastname;
            public int age;
            public grades stGrade;
        }

            
        public static void Main (string[] args)
        {
            student student1;
            student student2;
            student student3;

            student1.firstname = "Sara";
            student1.lastname = "Longman";
            student1.age = 20;
            student1.stGrade = grades.Excellent;

            student2.firstname = "Ahmed";
            student2.lastname = "Fahmy";
            student2.age = 19;
            student2.stGrade = grades.Good;

            student3.firstname = "Mohamed";
            student3.lastname = "Fathy";
            student3.age = 21;
            student3.stGrade = grades.Fair;
                
            student[] arrStudents = {student1, student2, student3};

            foreach (student s in arrStudents) {
                Console.WriteLine (s.firstname);
            }
        }
    } 

The output of this code should be:

Sara
Ahmed
Mohamed

The new part here is the foreach loop. You declare a variable (s) of type student and inform C# that this variable type is of the same type as the contents of arrStudents array. Having done this, the s variable would hold the value of each variable in the array. You don’t need to know the length of the array; you don’t need to make sure you access an array element that is out of the array boundaries; the foreach loop does this automatically for you. Inside the loop body you can treat the s variable the same way you treat any student variable.

But one shortcoming of the for loop arrays is that you have read-only access to the array elements. That is, you are not allowed to change the value of any variable. Consider this change in the above example:

foreach (student s in arrStudents) {
                s.firstname = "This won't work";
                Console.WriteLine (s.firstname);
            } 

This code will not run and will raise an error because you tried to change the value of firstname of the student variable. In this case you have to revert to the for loop.

Conclusion
In this article, we have talked about Arrays.

  • Arrays are collections of objects of the same data type.
  • Array elements are accessed via zero-based, ordered indexes.
  • To loop on the elements of an array, we could use either for or foreach

The next article will talk about Strings. So, stay here and don’t miss it.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -