C Sharp Test Question 7

You are developing a text processing application by using the .NET Framework. You write the following code to iterate over a collection of strings and populate a ListBox control with the values it contains (line numbers are for reference only). The GetStrings function returns an array of strings.

01: StringCollection myStrCol = new StringCollection();
02: myStrCol.AddRange(GetStrings());
03: StringEnumerator myEnumerator = myStrCol.GetEnumerator();

You need to add code to populate the ListBox control.

What code should you add?

C Sharp Test Question 7

C Sharp Test Question 7

Question 7 Explanation:

You should add the following code after line 03 to populate the ListBox control:

while (myEnumerator.MoveNext())
lstStrings.Items.Add(myEnumerator.Current);

When you instantiate the enumerator, the Current property points to a location before the first element. You need to call MoveNext() to set the Current point to the first element.

Using the following code is incorrect because you attempt to use Current when it does not point to a valid location:

do
{
lstStrings.items.Add(myEnumerator.Current)
} while (myEnumerator.MoveNext())

Using the following code is incorrect because calling the Reset method brings the enumerator back to the position before the first element in the collection:

myEnumerator.Reset()
do
{
lstStrings.items.Add(myEnumerator.Current)
} while (myEnumerator.MoveNext())

Using the following code is incorrect because each time through the loop the enumerator is repositioned before the first element:

do
{
lstStrings.items.Add(myEnumerator.Current)
myEnumerator.Reset();
} while (myEnumerator.MoveNext())

Objective: 
Developing applications that use system types and collections

Sub-Objective:
1.4 Manage data in a .NET Framework application by using specialized collections (Refer System.Collections.Specialized namespace)