Pages

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:

var
  States: array[0..49] of String[2];
  Counties: StringList;
begin
  Counties:=TStringlist.Create;

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] 
        {
            "AL","AK","AZ","AR",
            "CA","CO","CT",
            "DE",
            "FL",
            "GA",
            "HI",
            "ID","IL","IN","IA",
            "KS","KY",
            "LA",
            "ME","MD","MA","MI","MN","MS","MO","MT",
            "NE","NV","NH","NJ","NM","NY","NC","ND",
            "OH","OK","OR",
            "PA",
            "RI",
            "SC","SD",
            "TN","TX",
            "UT",
            "VT","VA",
            "WA","WV","WI","WY"
        };

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("Maricopa");
            Counties.Add("Sacramento");
            Counties.Add("Los Angeles");
            Counties.Sort();
            string temp = "";
            foreach (string S in Counties)
            {
                temp += S + "\n";
            }
            MessageBox.Show(temp);
        }

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

No comments:

Share This!

Contact Us

Name

Email *

Message *