Previous Page
Next Page

Creating a Generic Method

As well as defining generic classes, you can also use the .NET Framework to create generic methods.

A generic method allows you to specify parameters and return type by using a type parameter in a manner similar to that used when defining a generic class. In this way, you can define generalized methods that are typesafe, and avoid the overhead of casting (and boxing in some cases). Generic methods are frequently used in conjunction with generic classes—you need them for methods that take a generic class as a parameter, or that have a return type that is a generic class.

You define generic methods by using the same type parameter syntax that you use when creating generic classes (you can also specify constraints). For example, the generic Swap<T> method shown below can be used to swap the values in its parameters. As this functionality is useful regardless of the type of data being swapped, it is helpful to define it as a generic method:

static void Swap<T>( ref T first, ref T second)
   T temp = first;
   first = second;
   second = temp;

You invoke the method by specifying the appropriate type for its type parameter. The following examples show how to use the Swap<T> method to swap over two ints, and two strings:

int a = 1, b = 2;
Swap<int>(ref a, ref b);
string s1 = "Hello", s2 = "World";
Swap<string>(ref s1, ref s2);
Just as instantiating a generic class with different type parameters causes the compiler to generate different types, each distinct use of the Swap<T> method causes the compiler to generate a different version of the method. Swap<int> is not the same method as Swap<string>; both methods just happen to have been generated from the same generic method and so exhibit the same behavior, albeit over different types.
Defining a Generic Method to Build a Binary Tree

The previous exercise showed you how to create a generic class for implementing a binary tree. The Tree<T> class provides the Insert method for adding data items to the tree. However, if you want to add a large number of items, repeated calls to the Insert method are not very convenient. In the following exercise, you will define a generic method called BuildTree that allows you to create a new binary tree from a list of data items. You will test this method by using it to construct a tree of characters.

Write the BuildTree method
  1. Using Visual Studio 2005, create a new project by using the Console Application template. In the New Project dialog box, name the project BuildTree and set the Location to \Microsoft Press\Visual CSharp Step By Step\Chapter 17. Select Create a new Solution from the Solution dropdown.

  2. On the Project menu, click Add Reference. In the Add Reference dialog box click the Browse tab. Navigate to the folder \Microsoft Press\Visual CSharp Step By Step\Chapter 17\BinaryTree\bin\Debug, click BinaryTree.dll, and then click OK.

    The BinaryTree assembly will be added to the list of references shown in the Solution Explorer.

  3. In the Code and Text Editor window, add the following using directive to the top of the Program.cs file:

    using BinaryTree;

    This namespace contains the Tree<T> class.

  4. Add a method called BuildTree method to the Program class. This should be a static method that takes a params array of T elements called data, and returns a Tree<T> object.

    The method definition should look like this:

    static Tree<T> BuildTree<T>(params T[] data)
    The params keyword was described in detail in Chapter 11, “Understanding Parameter Arrays.”
  5. The T type used for building the binary tree must implement the IComparable<T> interface. Modify the definition of the BuildTree method and add the appropriate where clause.

    The updated definition of the method should look like this:

    static Tree<T> BuildTree<T>(params T[] data) where T : IComparable<T>
  6. Add the statements shown below to the BuildTree method. These statements instantiate a new Tree object by using the appropriate type parameter, and then iterate through the params list, adding each item to the tree by using the Insert method.

    The tree is passed back as the return value:

    static Tree<T> BuildTree<T>(params T[] data) where T : IComparable<T>
        Tree<T> sortTree = new Tree<T> (data[0]);
        for (int i = 1; i < data.Length; i++)
        return sortTree;
Test the BuildTree method
  1. In the Main method of the Program class, add the following statements that create a new Tree for holding character data, populates it with some sample data by using the BuildTree method, and then displays it by using the WalkTree method of the Tree:

    Tree<char> charTree = BuildTree<char>('Z', 'X', 'A', 'M', 'Z', 'M', 'N');
  2. On the Build menu, click Build Solution. Verify that the solution compiles, correcting any errors if necessary.

  3. On the Debug menu, click Start Without Debugging.

    When the program runs, the character values will be displayed, in order:

    A, M, M, N, X, Z, Z

  4. Press the Enter key to return to Visual Studio 2005.

Previous Page
Next Page