OTHER GENERIC TYPES

In addition to methods and classes, structs, delegates, and interfaces can also have type parameters. Structs and interfaces are obvious; the syntax looks much like that of classes:

public struct MyPoint<T> where T : struct {

  public MyPoint(T x, T y) {

    this.x = x;

    this.y = y;

  }

 

  private readonly T x;

  public T X {

    get { return x; }

  }

 

  private readonly T y;

  public T Y {

    get { return y; }

  }

}

 

public interface IListItem<T> {

  T Value { get; }

  ListItem<T> Prepend(T value);

}

Even with delegates there’s nothing surprising about the syntax. Following is an example of an alternative Factory implementation called ParameterFactory that uses a creation delegate instead of relying on the new() constraint and using a default constructor:

public delegate R CreateDelegate<T, R>(T param);

 

public class ParameterFactory<T, R> {

  CreateDelegate<T, R> createDelegate;

  public ParameterFactory(CreateDelegate<T, R> createDelegate) {

    this.createDelegate = createDelegate;

  }

 

  // ...

}

This includes the declaration of the CreateDelegate, which represents a function that takes a parameter of type T and returns a value of type R.

image

This is a good example of a statement that was made in Chapter 3, where the standard delegate types Func<...> were introduced. The ParameterFactory works with its own delegate type CreateDelegate instead of ...

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.