GENERIC CLASSES

It is also possible to add type information to classes. The scope of the type parameter is the entire class in this case, but it is used exactly the same way: in the place of a type. Here is an example of an (incomplete) linked list implementation:

public class ListItem<T> {

  public ListItem(T value) {

    this.value = value;

  }

 

  private ListItem(T value, ListItem<T> next) : this(value) {

    this.next = next;

  }

 

  private readonly T value;

  public T Value {

    get {

      return value;

    }

  }

 

  private ListItem<T> next;

 

  public ListItem<T> Prepend(T value) {

    return new ListItem<T>(value, this);

  }

}

The class ListItem has a generic type parameter T. This is the type encapsulated in the ListItem container, and it is used throughout the class in a variety of places where an explicit type could also be mentioned. The use of the generic type makes the ListItem more flexible, allowing it to encapsulate information of any other kind.

At the same time, the generic type system makes checking of types at compile time more powerful. For instance, the Prepend method is written in such a way that only values of type T will be accepted. From the perspective of any one instance of the ListItem class, T is fixed — in other words, the new value will always need to be of the same type as that of the current instance. Look at this code that uses the class:

private static void ListTest( ) {

  var intItem = new ListItem<int>(10);

 

  // Prepending further ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.