03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

324 ❘ CHAPTER 14 Collection Classes<br />

A single ArrayList object can hold objects of many different kinds. For example, the following<br />

code creates an ArrayList, adds several items of different types to it, and then loops through the<br />

list displaying the values.<br />

ArrayList list = new ArrayList();<br />

list.Add("What");<br />

list.Add(this);<br />

list.Add(7331);<br />

list.Add(new Bitmap(32, 32));<br />

foreach (object obj in list)<br />

Console.WriteLine(obj.ToString());<br />

The following text shows the result.<br />

What<br />

WindowsFormsApplication1.Form1, Text: Form1<br />

7331<br />

System.Drawing.Bitmap<br />

StringCollection<br />

The System.Collections.Specialized namespace’s StringCollection class is similar to<br />

ArrayList, except that it can hold only strings. Because it works only with strings, this class provides<br />

some extra type checking that the ArrayList does not. For example, if your program tries to add an<br />

Employee object or Bitmap to a StringCollection, the collection throws an exception.<br />

A StringCollection can hold duplicate values and null values.<br />

The following code shows how the UseStringCollection example program, which is available for<br />

download on the book’s website, demonstrates a StringCollection.<br />

// The values.<br />

private StringCollection Values = new StringCollection();<br />

// Add a value to the collection.<br />

private void addButton_Click(object sender, EventArgs e)<br />

{<br />

Values.Add(valueTextBox.Text);<br />

valueTextBox.Clear();<br />

valueTextBox.Focus();<br />

ListValues();<br />

}<br />

// Display the name/values groups.<br />

private void ListValues()<br />

{<br />

valueListBox.Items.Clear();<br />

foreach (string value in Values)<br />

{<br />

valueListBox.Items.Add(value);<br />

}<br />

}<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!