Building a Class that Implements IEnumerable

Building a Class that Implements IEnumerable

Recall from the earlier section "Specifying a DataSource" that any object that implemented the IEnumerable interface can be assigned as a DataSource. To prove this point, let's take a moment to create our own class that implements IEnumerable, and then use this class as a DataSource for one of the data Web controls.

Because we want to create a class that can be enumerated, we need some way to store the data that can be enumerated. For example, imagine that we're working on the postal service's Web site, and we want a collection of shipping options. Although we could implement this as a simple collection (perhaps as an ArrayList), we might also want to implement it as its own class (perhaps it also has to have a variety of methods and events). Clearly, we would need to use some sort of private variable to store the various shipping options.

Creating the Enumerable Class

For this exercise, let's just use an array. Specifically, we will use an array of integers that will hold the first 20 Fibonacci numbers.

NOTE

The Fibonacci sequence is a series of numbers defined as follows: the first two numbers are both 1. The ith Fibonacci number is defined as the sum of the i 1 and i 2 Fibonacci numbers. Therefore, the sequence is 1, 1, 2 (which is 1+1), 3 (2+1), 5 (3+2), 8 (5+3), and so on.


The code for the class can be found in Listing 2.4. Because this class implements IEnumerable (line 4), it must have a GetEnumerator method that returns an object that implements IEnumerator. Because we are storing the Fibonacci series in an array, we can simply return the array's enumerator via the Array class's GetEnumerator method (lines 24 through 28). (The reason the Array class has a GetEnumerator method is because it implements the IEnumerable interface that's the reason why we opted to store the Fibonacci numbers in an array, to make our task easier!)

Listing 2.4 The FibSeries Class Implements the IEnumerable Interface
  1: using System;   2: using System.Collections;   3:   4: public class FibSeries : IEnumerable   5: {   6:   // we must have something to enumerate over,   7:   // let's just use an integer array   8:   int [] data;   9:  10:   public FibSeries(int size)  11:   {  12:     // create the array  13:     data = new int[size];  14:  15:     // populate the array  16:     data[0] = 1;  17:     data[1] = 1;  18:  19:     for (int i = 2; i < size; i++)  20:       data[i] = data[i-1] + data[i-2];  21:   }  22:  23:   // since we implement IEnumerable we must provide a GetEnumerator method  24:   public IEnumerator GetEnumerator()  25:   {  26:     // simply return the array's enumerator  27:     return data.GetEnumerator();  28:   }  29: } 

As can be seen in Listing 2.4, the FibSeries class has a private integer array, data, defined on line 8. This array will hold a number of Fibonacci numbers. The constructor (lines 10 through 21) requires an input parameter of type integer, which consists of the amount of Fibonacci numbers the user wants. There should definitely be some bounds-checking going on here, ensuring that size isn't negative or less than 2. I leave this as an exercise to the reader.

On lines 16 and 17, the first two Fibonacci numbers are added to the data array. Then, a loop populates the remainder of the array values.

Compiling the Class and Deploying the Assembly

Once we've written this class, we'll need to compile it into an assembly (a DLL). If you are using Visual Studio .NET, you'll want to create a C# class. Simply compile the project, and the assembly is ready. If you do not have Visual Studio .NET, you will have to use the command line compiler. Start by creating a text file named FibSeries.cs, and copy in the text from Listing 2.4. Drop to the command prompt, navigate to the directory where FibSeries.cs is located, and type

 csc /t:library FibSeries.cs 

This will create an assembly named FibSeries.dll. Regardless of whether you use Visual Studio .NET or if you compile the assembly via the command line, you'll need to copy the DLL to our ASP.NET project's /bin folder. Once the DLL is there, we can use the class in our ASP.NET Web page.

Using the Class as a DataSource

Listing 2.5 illustrates the use of the FibSeries class as a DataSource for the DataList Web control.

Listing 2.5 The FibSeries Class Can Be Used As a DataSource
  1: <script runat="server" language="C#">   2:   3:     void Page_Load(Object sender, EventArgs e)   4:     {   5:       FibSeries fibTest = new FibSeries(25);   6:   7:       Fib.DataSource = fibTest;   8:       Fib.DataBind();   9:     }  10:  11: </script>  12:   13: <asp:DataList runat="server"  RepeatColumns="5"  14:     CellPadding="5" ItemStyle-HorizontalAlign="Right"  15:     ItemStyle-BorderStyle="Solid" RepeatDirection="Horizontal">  16:   <ItemTemplate>  17:     <%# String.Format("{0:#,###}", Container.DataItem) %>  18:   </ItemTemplate>  19: </asp:DataList> 

Because the FibSeries.DLL file has been copied into our ASP.NET Web site's /bin directory, we can start using the FibSeries class. On line 5, we create a new instance of the FibSeries class, specifying that we'd like the first 25 Fibonacci numbers. On line 7, the FibSeries instance fibTest is assigned to the DataList's DataSource, and on line 8, the DataBind() method is called.

In lines 13 19, the DataList is declared. We create a 5x5 grid with the RepeatColumns property. The RepeatDirection property indicates that the items should repeat horizontally as opposed to vertically in the rendered HTML table. The ItemStyle-HorizontalAlign property setting on line 14 dictates that the cells of the DataList should be right-aligned, while the ItemStyle-BorderStyle property setting on line 15 indicates that a border should be displayed. (We'll cover these two aesthetic properties and more in the next chapter.)

Finally, in the ItemTemplate, we use a more complicated data-binding expression than we have seen thus far. Because our DataSource returns integers during each iteration (recall that we are enumerating over an integer array), we could just use <%# Container.DataItem %> for our data-binding syntax. However, we can make the numbers easier to read by having commas inserted every three decimal places. To accomplish this, we use the String.Format method to apply formatting to the Container.DataItem value. Don't concern yourself with the details of the String.Format method just yet; we'll get to that in Chapter 3. For now, just note that we can use the result of a method call in our data-binding syntax (we'll discuss this, as well, in the next chapter).

A screenshot of Listing 2.5 when viewed through a browser can be seen in Figure 2.3. Note that there is a border around each table cell and that the cells are right-aligned. Furthermore, notice that those numbers longer than three digits have commas every three digits (courtesy of the String.Format call).

Figure 2.3. The first 25 Fibonacci numbers are shown using a DataList.

graphics/02fig03.gif



ASP. NET Data Web Controls Kick Start
ASP.NET Data Web Controls Kick Start
ISBN: 0672325012
EAN: 2147483647
Year: 2002
Pages: 111

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net