Home

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 Notepad and, to create a new program, in the empty document, type the following:
     
    using System;
    
    namespace CommercialStore1
    {
        public class Exercise
        {
            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);
            }
        }
         
        class Program
        {
            static int Main(string[] args)
            {
                Exercise exo = new Exercise();
                Exercise.CItem Part;
    
                Part = new Exercise.CItem();
                Part.Item = 97.43;
                exo.Add(Part);
    
                Part = new Exercise.CItem();
                Part.Item = 274.87;
                exo.Add(Part);
    
                Part = new Exercise.CItem();
                Part.Item = 8.7873;
                exo.Add(Part);
    
                Part = new Exercise.CItem();
                Part.Item = 2764.4;
                exo.Add(Part);
    
                Part = new Exercise.CItem();
                Part.Item = 92.4662;
                exo.Add(Part);
    
                Part = new Exercise.CItem();
                Part.Item = 66800.85;
                exo.Add(Part);
    
                Console.WriteLine("-=- List of Items -=-");
    
                for (int i = 0; i < exo.Count(); i++)
                {
                    Exercise.CItem One = exo.Retrieve(i);
    
                    exo.ShowItem(One.Item);
                }
    
                Console.WriteLine("\nNumber of Items: {0}\n", exo.Count());
    
                return 0;
            }
        }
    }
  2. Save the file as Exercise.cs in a new folder named CommercialStore1 in your CSharpLessons folder
  3. Open the Command Prompt and switch to the folder that contains the file
  4. Compile the Exercise.cs file and 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 . . .
  5. Return to Notepad

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 and return to the Command Prompt
  3. Compile the Exercise.cs file and execute the Exercise application
  4. Notice that it works fine

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(string[] args)
        {
            . . .
    
            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. Save the file and return to the Command Prompt
  3. Compile the Exercise.cs file and execute the Exercise application
  4. Notice that it works fine
 

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