Information Technology Reference
In-Depth Information
Generic Interfaces
Generic interfaces allow you to write interfaces where the parameters and return types of inter-
face members are generic type parameters. Generic interface declarations are similar to
non-generic interface declarations, but have the type parameter list in angle brackets after
the interface name.
For example, the following code declares a generic interface called
IMyIfc
that declares a
single method.
Generic class
Trivial
implements the generic interface.
Main
instantiates two objects of the generic class: one with type
int
, and the other with
type
string
.
Type parameter
↓
interface IMyIfc<T> // Generic interface
{
T ReturnIt(T inValue);
}
Type parameter
Generic interface
↓
↓
class Trivial<S> : IMyIfc<S> // Generic class
{
public S ReturnIt(S inValue) // Implement interface
{
return inValue;
}
}
class Program
{
static void Main()
{
Trivial<int> TrivInt = new Trivial<int>();
Trivial<string> TrivString = new Trivial<string>();
Console.WriteLine("{0}", TrivInt.ReturnIt(5));
Console.WriteLine("{0}", TrivString.ReturnIt("Hi there."));
}
}
The output of this code is the following:
5
Hi there.