Share This!

Sunday, August 12, 2007

Creating and Using Arrays in C#

Most of my history is with Borland/Inprise/Borland/CodeGear Delphi, so what I am trying to demonstrate is how to take a construct like these:

  States: array[0..49] of String[2];
  Counties: StringList;

In this demo, States is an array of 50 string[2] variables indexed from 0. Counties is a re-sizable list of strings. A fixed array is a data type, while a TStringList is a class object. How do we do arrays in C#?

Here is an example of the declaration (and optional initialization) of a fixed array...

        public string[] States = new string[50] 

Here is a collection, the equivalent of a Stringlist or TList.

        public ArrayList Counties = new ArrayList();

Now I'll pop some dialog messages to show we know what's in the array and in the collection... of course we have to first load something into the collection, so I created a button and wrote this code...

        private void button1_Click(object sender, EventArgs e)
            MessageBox.Show("State 23 is " + States[23]);
            Counties.Add("Los Angeles");
            string temp = "";
            foreach (string S in Counties)
                temp += S + "\n";

This code when compiled (after you resolve the missing using clause) gives this result...

No comments:

Post a Comment

Contact Us


Email *

Message *