To make a generic type whose argument belongs to a type class, you may instantinate a type class for this particular type using TypeClass<T>.Instance.

Note, that current versions of .NET languages do not check that type belongs to a type class during compile time. So if type parameter will not satisfy all type class's requirements, you will get TypeLoadException at runtime while trying to use instantinated type. TypeClassCheck tool can be used to verify that all type class instantinations are valid. It can be used like "TypeClassCheck.exe pathToAssemblyToBeChecked" (see Post-Build event in TypeClassSample project).

Here is a simple example that uses TypeWithZero<T> type class defined in previous article:
public class Vector3D<T>
  public T X, Y, Z;

  static readonly TypeWithZero<T> zero = TypeClass<TypeWithZero<T>>.Instance;
  public static Vector3D<T> Zero
    get{ return new Vector3D<T>{ X = zero.Zero, Y = zero.Zero, Z = zero.Zero }; }

So this class uses type class's Zero static member to provide its own Zero static member (which in turn makes any Vector3D<T> type itself suitable for TypeWithZero<T> type class).

Last edited Nov 25, 2010 at 12:04 AM by LostTheBlack, version 5


No comments yet.