Just as in generic classes, it is useful to define generic interfaces. It's useful to define generic interfaces for collections such as linked lists.
In this example, we are defining a generic interface that requires T to be a reference type.
// File: GenericInterfaces.cs
using System;
public interface INode<T> where T:class
{
string Value
{
get;
}
T Next
{
get;
}
}
public class PersonNode : INode<PersonNode>
{
private string name;
private PersonNode next;
public PersonNode(string name, PersonNode next)
{
this.name = name;
this.next = next;
}
public string Value
{
get
{
return name;
}
}
public PersonNode Next
{
get
{
return next;
}
}
}
public class Program
{
static void Main()
{
PersonNode danNode = new PersonNode("dan", null);
PersonNode sabetNode = new PersonNode("sabet", danNode);
PersonNode mikeNode = new PersonNode("mike", sabetNode);
PersonNode node = mikeNode;
while (node != null)
{
Console.WriteLine(node.Value);
node = node.Next;
}
Console.ReadLine();
}
}