1.15. Jagged Arrays

Now that we've stored each line of text within an ArrayList container, we next want to iterate across the elements, separating each line into an array of the separate words. We'll need to store these arrays because they become fodder for the function implementing the word count. But this storage proves something of a problem—or at least a puzzle. Problem or puzzle, jagged arrays provide a solution.

If we are only reading the elements of the container, the foreach loop is the preferred iteration method. It spares us the explicit cast of the object element to an object of its actual type. Any other element assignment requires the cast:

 for( int ix = 0; ix < text.Count; ++ix ){ string str = ( string )text[ ix ]; // ... } // ...

Get C# Primer: A Practical Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.