In this article we will get a little deeper into some C# programming by looping through arrays and practicing using types (which are basically objects).
In C#, everything is an object, including arrays. I understand the concept of an array, but I really wanted to get more comfortable with using arrays in C#.
So I created a very simple Console Application that uses loops to create an array and output the results to the console. I also wanted to get more familiar with working with classes and objects in the C# language.
The first thing I did in C# Express Edition was create a new project. I then right clicked the project and selected Add: Class and named the class Stores.
This is the Stores.cs Class file:
using System; using System.Collections; namespace Stores { public class Stores { // this will contain all the store data public ArrayList stores_arraylist = new ArrayList(); /* * Create the Stores */ public void getStores() { string[] currentStore; // add 10 stores for (int storeNumber = 1; storeNumber < 11; storeNumber++) { // add the data for the current store currentStore = new string[] { "Store #" + storeNumber, "Number of Customers: " + storeNumber }; // add the current store information to the ArrayList stores_arraylist.Add(currentStore); } } /* * Print out each Store */ public void printStores() { // first loop throught each item in the arrayList foreach (string[] store in stores_arraylist) { Console.WriteLine("-------"); // now loop through each item in the array foreach (string store_info in store) { Console.Write(store_info + "n"); } } } } }
I then added this code to the Main method in Program.cs file:
Stores myStores = new Stores(); myStores.getStores(); myStores.printStores();
Press Ctrl + F5 and you should see each stores’ info printed to the console.
C# does not have what we call associated arrays in PHP (which basically are keys/indexes that are text). This is good in a sense, because you know that the first key in a C# array will always be 0, and then 1, etc… I’m a little bummed because I usually made the primary key in a table the key/index of each element in an array in PHP (but there really is no downside in the way C# is setup). With that said, I am really enjoying learning PHP.
PHP is starting to look more like a bath toy compared to C#. In fact, I’m learning why some people have a hard time considering PHP a true OO programming language….but PHP does what it was meant to do, which was to create websites quickly.