Generics - Methods


Methods within a generic class that make use of the generic type parameter are automatically generic. However, it is possible that a method has its own type parameter and therefore be generic even within a non-generic class. The next example contains a non-generic class that possesses two generic methods.

// Generic10 - Generic Methods

using System;

class X
{
    object o;

    public void f<T>(T t)
    {
        o = t;
    }

    public T g<T>()
    {
        return (T)o;
    }
}

class Program
{
    static void Main()
    {
        X x = new X();

        x.f("Hello world");
        Console.WriteLine("Object = {0}", x.g<string>());

        x.f(100);
        Console.WriteLine("Object = {0}", x.g<int>());
    }
}

The method X.f is generic even though X is not. Likewise, X.g is generic. It is also possible that X is generic but f and g possess a different generic parameter from the class generic parameter or parameters.

The calls to f use implicit type arguments. The type argument was inferred from the type of the parameter. This process is referred to as type inference. The parameter's type (string or int) determines the type T in X.f<T>. Such is not possible for X.g because only the return type is parameterized. Therefore, in the case of X.g, explicit type arguments were required and specified.

The general form of a generic method is shown below.

return-type method-name<type-parameter-list>(parameter-list)
{
 ...
}

Constraints may be added to this form. When a constraint is used it occurs after the right parenthesis and before the brace.