The Leading Educational Resource for IT Professionals

TechTip: C# for RPGers - More on Arrays and a Different FOR Loop

by Victoria Mack November 04, 2016 0 Comments

Let’s continue to explore C# arrays and introduce a different FOR loop. It’s a very useful tool that has no equivalent in RPG.

 

In the last TechTip in this C# series, I introduced the array data type and showed how it’s defined and used. Now let’s explore some of its properties and methods, with the help of a different FOR loop: ForEach.

 

Let’s use the code from the previous TechTip as a starting point for this one. I’m not going to change that code, but it might be useful to have it at hand to compare code features and for you to play around with what you’ll learn this time. Open the “IntroducingArrays” project, by navigating to the respective folder and opening the “IntroducingArrays.sln” file. Now position the cursor at the end of the myFirstArray definition line (it should be line 9 of the source code) and press Enter. Type, or copy and paste, the following lines of code:

 

// it's also possible to initialize the array when it's being defined

String[] serverNames = new String[]

                       { "AS/400"

                       , "iSeries"

                       , "System i"

                       , "IBM i" };

 

This is a different way to define an array, which combines definition and initialization on the same statement. Note that the length of the array is automatically determined by the compiler, based on the number of elements on the list. This piece of code will create a four-element array of strings and initialize it with “AS/400”, “iSeries”, “System i”, and “IBM i”.

 

Introducing the foreach Loop

Now place the cursor at the end of the last Console.ReadKey(); line and press Enter. To output the values of the serverNames array, I could write a FOR loop, similar to the ones used in the previous TechTip. Actually, I could simply copy and paste the last FOR loop and switch the array name, replacing myFirstArray by serverNames. Instead of doing that, I’ll introduce a different type of FOR loop, created to facilitate the handling of collections of data, like arrays and lists. (By the way, the List data type will be discussed in the next TechTip.) This FOR loop variant, aptly named foreach, allows you to perform a set of operations to each element of a data collection. In this case, I’ll use it to output the value of each element of the serverNames array:

 

Console.WriteLine("The chronologically sorted string array:");

// looping through the array

// using foreach and outputing each element

foreach (string name in serverNames)

{

Console.WriteLine(name);

}

Console.ReadKey();

 

Note how simple and elegant this loop structure is. I simply “tell” the compiler the name of the array as well as the data type and name of each of the elements of that array. In this example, I’m using a string variable (after all, my array is an array of strings) called name. The syntax is almost natural English: “for each name in server names do this…”. Then I can use the name variable to refer to each of the elements of the arrayall of this without indexes or iterators.

 

You’ll see that the foreach loop is particularly useful to iterate over complex data types, either native or user-defined.

 

More Array Properties and Methods

My serverNames array now contains the names the IBM i has had over the years (assuming I got them all; feel free to correct me) in chronological order. Suppose I want to reorder the elements of the array and switch from a chronological to an alphabetic order. I could write a piece of code to sort the array or look up one of the gazillion versions of that sorting algorithm online. Instead, I’ll use a method of the Array class: the Sort method. If you remember what I explained a few TechTips ago, Visual Studio presents a list of available properties and methods of an object when you type the object name followed by a dot (“.”). However, if you type “serverNames.” you won’t find the Sort method. This and many other methods are not available on the variables defined by the programmer. Instead, they are part of the Array class itself. You’ve seen something similar to this before: I’ve been using the WriteLine method of the Console class to output “things.” However, I didn’t define an object or variable named Console. It’s simply made available by C# (it’s a bit more complicated than this, but this will be enough for now). Similarly, I can invoke methods of the Array class by typing “Array.” and selecting the appropriate method from the list. So now let’s sort the serverNames array by either typing, or copying and pasting, the following code to the line below the last line you inserted (that would be the ReadKey() line):

Array.Sort(serverNames);

 

To see the result, copy and paste the foreach loop to after the array sorting line. If you run the program, you’ll see first the original, chronologically ordered list of server names and then the same list, now alphabetically sorted. The same conceptually simple type of solution is available for other common problems, such as clearing an array. Naturally, you can use a FOR or foreach loop structure to fly through the entire array, zapping each element’s value. Or you can use Array.Clear.

 

The Clear method has enough flexibility to scrub clean an entire array or simply a part of it, because it allows you to specify where to start, with the <start position> parameter, and how many elements to clear, with the number of elements from that position on, with the <length to clear> parameter. The method’s complete syntax, which reminds me of the Substring method I discussed in a previous TechTip, is the following:

 

Array.Clear(<array name>, <start position>, <length to clear>);

 

If I wanted to clear the serverNames array, I’d simply write:

 

// clearing an entire array with a single instruction

Array.Clear(serverNames, 0, serverNames.Length);

 

In order to confirm it’s really scrubbed clean, let’s output the value of the first element of the array:

 

// showing the first element of the array:

// it's now blank, the default value for a string ("")

Console.WriteLine("And now first position of the array, after being cleared:");

Console.WriteLine(serverNames[0]);

Console.ReadKey();

 

Feel free to explore the Array class methods and experiment with this piece of code on your own; you’ll find the complete source code of the last two TechTips below. As usual, Visual Studio’s embedded (and online) documentation will guide you through the details, and if that’s not enough, there are tons of forums where you can get help.

 

Arrays are powerful data structures but suffer from a major design flaw: They can’t be re-dimensioned. Once created, their length will remain the same. You can copy an array’s elements to a new, larger array (using the object’s CopyTo method, which I haven’t explained yet), but you’ll end up with the same problem, eventually. There’s another data structure, with some similarities with the Array but free of this annoying flaw: the List. I’ll be talking about it in the next TechTips.

 

That’s all the time I have! I’ll leave you with the complete source code of these two TechTips:

using System;

 

namespace IntroducingArrays

{

   class Program

   {

       static void Main(string[] args)

       {

           int[] myFirstIntArray = new int[10];

 

           // it's also possible to initialize the array when it's being defined

           String[] serverNames = new String[]

                                   { "AS/400"

                                   , "iSeries"

                                   , "System i"

                                   , "IBM i" };

 

           // assigining 1 to the first position of the array

           myFirstIntArray[0] = 1;

           // looping through the array, starting on position 1

           for (int index = 1; index <= 9; index++)

           {

               myFirstIntArray[index] = index + 1;

           }

           // displaying the value of the array's third position

           Console.WriteLine(myFirstIntArray[2]);

           // ReadKey is used to "pause" the display

           // until a key is pressed

          Console.ReadKey();

           // looping through the array, to output the value of each element

           for (int index = 0; index < myFirstIntArray.Length; index++)

           {

               Console.WriteLine(myFirstIntArray[index]);

            }

           // ReadKey is used to "pause" the display

           // until a key is pressed

           Console.ReadKey();

 

           Console.WriteLine("The chronologically sorted string array:");

           // looping through the array

           // using foreach and outputing each element

           foreach (string name in serverNames)

           {

               Console.WriteLine(name);

           }

           Console.ReadKey();

           // sort the array using Array.Sort(<array name>)

           Array.Sort(serverNames);

           // show the array contents again

           Console.WriteLine("Now the alphabetically sorted string array:");

           // looping through the array

           // using foreach and outputing each element

           foreach (string name in serverNames)

           {

               Console.WriteLine(name);

           }

           Console.ReadKey();

           // clearing an entire array with a single instruction

           Array.Clear(serverNames, 0, serverNames.Length);

           // showing the first element of the array:

           // it's now blank, the default value for a string ("")

           Console.WriteLine("And now first position of the array, after being cleared:");

          Console.WriteLine(serverNames[0]);

           Console.ReadKey();

       }

   }

}

 




Victoria Mack
Victoria Mack

Author



Also in MC Press Articles

Customer (Citizen) Identity and Access Management

by Graham Williamson June 13, 2017 0 Comments

As a major trend in the IDM sector, consumerization has become easier and exponentially more important. Digital transformation will literally put a significant segment of the SME market out of business and propel a significant number of SMEs to new levels of prosperity.

Continue Reading →

Federated Authentication – there is no Plan B

by Graham Williamson June 05, 2017 0 Comments

Federated authentication is essential for businesses. It's the only way to effectively manage external access to business systems and it's absolutely necessary in order to manage authentication to SaaS apps. if you don't want to expose your identity records to potential compromise.

Continue Reading →

Access Control – RBAC & ABAC

by Graham Williamson May 04, 2017 0 Comments

Access Control is the core of the identity and access management task. Once we have correctly provisioned user data into the enterprise’s identity service we need to leverage it for access control. The vast majority of organizations use role-based access control, but increasingly, access control based on attributes is gaining traction.

Continue Reading →