Understanding Generics—Creating Generic Interfaces

Jump to: navigation, search
Visual C# Tutorials

Understanding Generics

© 2006 Andrew Troelsen

Creating Generic Interfaces

As you saw earlier in the chapter during the examination of the System.Collections.Generic namespace, generic interfaces are also permissible (e.g., IEnumerable<T>). You are, of course, free to define your own generic interfaces (with or without constraints). Assume you wish to define an interface that can perform binary operations on a generic type parameter:

public interface IBinaryOperations<T>
   T Add(T arg1, T arg2);
   T Subtract(T arg1, T arg2);
   T Multiply(T arg1, T arg2);
   T Divide(T arg1, T arg2);

Of course, interfaces are more or less useless until they are implemented by a class or structure. When you implement a generic interface, the supporting type specifies the placeholder type:

public class BasicMath : IBinaryOperations<int>
   public int Add(int arg1, int arg2)
   { return arg1 + arg2; }
   public int Subtract(int arg1, int arg2)
   { return arg1 - arg2; }
   public int Multiply(int arg1, int arg2)
   { return arg1 * arg2; }
   public int Divide(int arg1, int arg2)
   { return arg1 / arg2; }

At this point, you make use of BasicMath as you would expect:

static void Main(string[] args)
   Console.WriteLine("***** Generic Interfaces *****\n");
   BasicMath m = new BasicMath();
   Console.WriteLine("1 + 1 = {0}", m.Add(1, 1));

If you would rather create a BasicMath class that operates on floating-point numbers, you could specify the type parameter as so:

public class BasicMath : IBinaryOperations<double>
   public double Add(double arg1, double arg2)
   { return arg1 + arg2; }

prevpp.png  nextpp.png
C# Online.NET