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

Gifts to Give Yourself This Holiday

by Victoria Mack December 21, 2016 0 Comments

It’s the holiday season, and everyone is in the gift-giving mood. Be sure you don’t forget to invest in your company and career.

brian mayWritten by Brian May

It’s a special time of the year. Family gatherings for the holidays, football season, and time in the woods all make this one of my favorite seasons. The month of December is also unique for IT departments. December is certainly not business as usual for most of us.

It’s time for budgets. That may mean requesting budget items for next year or spending surplus budget before the end of the year. It’s often when project work slows down a bit as end users, and IT staff alike, take time away from the office. It’s a time when stress is often at its lowest, and it’s just easier to get some things done.

Continue Reading →

SQL 101: Tools of the Trade - i Navigator’s Run SQL Scripts

by Victoria Mack December 21, 2016 0 Comments

A more “modern” alternative to STRSQL, discussed in the last two articles, is the i Navigator’s Run SQL Scripts tool. Let’s explore it together, shall we?

rafael victoria preiraWritten by Rafael Victória-Pereira

While STRSQL is a green-screen tool, Run SQL Scripts is part of the i Navigator package. You can access it by choosing the Run SQL Scripts option, either from the bottom-right pane of the i Navigator window after you’ve chosen the Databases tree node from the right panel, as shown in Figure 1, or by right-clicking the database name and choosing the respective option.

Continue Reading →

Energy, Vibe, and Atmosphere

by Victoria Mack December 19, 2016 0 Comments

This is IT. We must be willing to bend.

steve pitcherWritten by Steve Pitcher

With a growing emphasis in talking about the state of the current IBM i workforce, also known as the “IBM i skills shortage,” it behooves oneself to keep the noise level to a minimum in order to make even-keeled decisions. In short, don’t necessarily believe all the hype you read.

I’d like to think of this as an extension piece to “The IBM i Skills Shortage Myth.” It’s not necessarily a “part two” per se, but more of a story that runs parallel. I’ve been trying to write this for about six weeks, but some things are just hard to put into words, especially when they involve how you feel as opposed to what you know. Besides, writing what you know is easy. Writing what you feel leaves room for reader interpretation, so you have to be more careful.

Continue Reading →