Home

Generics: Generic Methods

 
 

Introduction

As is usually done, imagine you want to pass different types of values to various methods of a class to primarily accomplish the same purpose. You may be tempted to overloaded a method in various versions as follows:

using System;

public class Exercise
{
    // Display the value of an integer
    public void Show(int value)
    {
        Console.WriteLine(value);
    }

    // Display the value of a double-precesion value
    public void Show(double value)
    {
        Console.WriteLine(value);
    }

    // Display the value of a character
    public void Show(char value)
    {
        Console.WriteLine(value);
    }
}
public class Program
{
    static int Main()
    {
        Exercise exo = new Exercise();
        
        // Call the version of the method that displays an integer
        exo.Show(246);
        
        // Call the version of the method that displays a character
        exo.Show('G');
        
        // Call the version of the method that displays a decimal
        exo.Show(355.65);
        
        return 0;
    }
}

This would produce:

246
G
355.65
Press any key to continue . . .

We passed a constant value directly to the method when we called it. Remember that you can also first declare a variable, assign it a value, and then pass that variable to the method. Here are examples:

public class Program
{
    static int Main()
    {
        Exercise exo = new Exercise();

        // Call the version of the method that displays an integer
        int Value1 = 246;
        exo.Show(Value1);

        // Call the version of the method that displays a character
        char Value2 = 'G';
        exo.Show(Value2);

        // Call the version of the method that displays a decimal
        double Value3 = 355.65;
        exo.Show(Value3);

        return 0;
    }
}

Although this is based on the concept of method overloading, another way you can solve this type of problem is to create one method that doesn't know the type of value that would be passed to it but the method is equipped to process the value appropriately. Based on the above program, you can create one method that takes an argument and it displays its value. To do this, at the time you are defining the method, you only let it know that it would receive an argument but you don't specify the type of value that it will process. Such a method is referred to as generic.

Practical LearningPractical Learning: Introducing Generics

  1. Start Microsoft Visual C# and create a Console Application named CommercialStore1
  2. To create a new class, on the main menu, click Project -> Add Class...
  3. Set the Name to StoreItem and press Enter
  4. Change the file as follows:
     
    using System;
    
    namespace CommercialStore1
    {
        class StoreItem
        {
            public class CItem
            {
                public double Item;
                public CItem Next;
            }
    
            public CItem Head = null;
            public int Size;
    
            public int Count()
            {
                return Size;
            }
    
            public int Add(CItem NewItem)
            {
                CItem Sample = new CItem();
    
                Sample = NewItem;
                Sample.Next = Head;
                Head = Sample;
    
                return Size++;
            }
    
            public CItem Retrieve(int Position)
            {
                CItem Current = Head;
    
                for (int i = Count() - 1; i > Position && Current != null; i--)
                {
                    Current = Current.Next;
                }
    
                return Current;
            }
    
            public void ShowItem(double item)
            {
                Console.WriteLine("Item: {0}", item);
            }
        }
    }
  5. Access the Program.cs file and change it as follows:
     
    using System;
    
    namespace CommercialStore1
    {
        class Program
        {
            static int Main()
            {
                StoreItem exo = new StoreItem();
                StoreItem.CItem Part;
    
                Part = new StoreItem.CItem();
                Part.Item = 97.43;
                exo.Add(Part);
    
                Part = new StoreItem.CItem();
                Part.Item = 274.87;
                exo.Add(Part);
    
                Part = new StoreItem.CItem();
                Part.Item = 8.7873;
                exo.Add(Part);
    
                Part = new StoreItem.CItem();
                Part.Item = 2764.4;
                exo.Add(Part);
    
                Part = new StoreItem.CItem();
                Part.Item = 92.4662;
                exo.Add(Part);
    
                Part = new StoreItem.CItem();
                Part.Item = 66800.85;
                exo.Add(Part);
    
                Console.WriteLine("-=- List of Items -=-");
    
                for (int i = 0; i < exo.Count(); i++)
                {
                    StoreItem.CItem One = exo.Retrieve(i);
    
                    exo.ShowItem(One.Item);
                }
    
                Console.WriteLine("\nNumber of Items: {0}\n", exo.Count());
                return 0;
            }
        }
    }
  6. Execute the application to see the result
     
    -=- List of Items -=-
    Item: 97.43
    Item: 274.87
    Item: 8.7873
    Item: 2764.4
    Item: 92.4662
    Item: 66800.9
    
    Number of Items: 6
    
    Press any key to continue . . .
  7. Close the DOS window

Generic Method Creation

A generic method is a method that can process a value whose type is known only when the variable is accessed. To create a generic method, on the right side of the name of the method, type the <> operator. Inside of this operator, enter a letter or a name, which is referred to as parameter type. Here is an example:

public class Exercise
{
    public void Show<TypeOfValue>()
    {
    }
}

One of the ways you can use the parameter type is to pass an argument to the method. You do this by preceding the name of the argument with the parameter type. Here is an example:

public class Exercise
{
    public void Show<TypeOfValue>(TypeOfValue value)
    {
    }
}

In the body of the method, you can process the argument as you see fit. At a minimum, and based on our earlier program, you can simply display the value by passing it to the Console.WriteLine() method. Here is an example:

public class Exercise
{
    public void Show<TypeOfValue>(TypeOfValue value)
    {
        Console.WriteLine(value);
    }
}

By tradition, most programmers and most documents use the letter T for the parameter type.

Practical LearningPractical Learning: Creating a Generic Method

  1. To create a generic method, change the ShowItem() method as follows:
     
    public void ShowItem<T>(T item)
    {
          Console.WriteLine("Item: {0}", item);
    }
  2. Save the file

Calling a Generic Method

As mentioned earlier, one of the particularities of a generic method is that, at the time it is defined, the method doesn't know the type of the parameter. This means that, when calling the method, you must make sure you clearly specify the type of value that will be processed. You can do this by directly passing (a constant of) the type of value that the method will process. Here are different examples of calling our Show() method:

using System;

public class Exercise
{
    public void Show<TypeOfValue>(TypeOfValue value)
    {
        Console.WriteLine(value);
    }
}

public class Program
{
    static int Main()
    {
        Exercise exo = new Exercise();

        // Call the version of the function that displays an integer
        int Value1 = 246;
        exo.Show(Value1);

        // Call the version of the function that displays a character
        char Value2 = 'G';
        exo.Show(Value2);

        // Call the version of the function that displays a decimal
        double Value3 = 355.65;
        exo.Show(Value3);
        
        return 0;
    }
}

When complied and executed, this program would produce:

246
G
355.65
Press any key to continue . . .

As an alternative, you can type the name of the method, followed by angle brackets. Inside of the brackets, enter the data type of the value that will be processed. After the angle brackets, open the parentheses and, inside of them, type the constant value that will be processed. Here are examples:

using System;

public class Exercise
{
    public void Show<TypeOfValue>(TypeOfValue value)
    {
        Console.WriteLine(value);
    }
}

public class Program
{
    static int Main()
    {
        Exercise exo = new Exercise();

        // Call the version of the function that displays an integer
        int Value1 = 246;
        exo.Show<int>(Value1);

        // Call the version of the function that displays a character
        char Value2 = 'G';
        exo.Show<char>(Value2);

        // Call the version of the function that displays a decimal
        double Value3 = 355.65;
        exo.Show<double>(Value3);
        
        return 0;
    }
}

You can also declare the value as a constant before passing it to the method.

Practical LearningPractical Learning: Calling a Generic Method

  1. To specify the parameter type of a generic method when calling it, change the Main() method as follows:
     
    class Program
    {
        static int Main()
        {
            . . .
    
            Console.WriteLine("-=- List of Items -=-");
    
            for (int i = 0; i < exo.Count(); i++)
            {
                Exercise.CItem One = exo.Retrieve(i);
    
                exo.ShowItem<double>(One.Item);
            }
    
            Console.WriteLine("\nNumber of Items: {0}\n", exo.Count());
            return 0;
        }
    }
  2. Execute the application and notice that it works fine
  3. Close the DOS window
 

Previous Copyright © 2006-2016, FunctionX, Inc. Next