Information Technology Reference
In-Depth Information
An Example Using Generic Interfaces
The following example illustrates two additional capabilities of generic interfaces:
￿
Like other generics, instances of a generic interface instantiated with different type
parameters are different interfaces.
￿
You can implement a generic interface in a non-generic type .
For example, the following code is similar to the last example, but in this case, Trivial is a
non-generic class that implements a generic interface. In fact, it implements two instances of
IMyIfc . One instance is instantiated with type int , and the other with type string .
interface IMyIfc<T> // Generic interface
{
T ReturnIt(T inValue);
}
Two different interfaces from the same generic interface
class Trivial : IMyIfc<int>, IMyIfc<string> // Non-generic class
{
public int ReturnIt(int inValue) // Implement int interface
{
return inValue;
}
public string ReturnIt(string inValue) // Implement string interface
{
return inValue;
}
}
class Program
{
static void Main()
{
Trivial TrivInt = new Trivial();
Trivial TrivString = new Trivial();
Console.WriteLine("{0}", TrivInt.ReturnIt(5));
Console.WriteLine("{0}", TrivString.ReturnIt("Hi there."));
}
}
This code produces the following output:
5
Hi there.
Search WWH ::




Custom Search