Anders Hejlsberg came up with a clever
trick to implement generic algorithms with the current C# generics implementation.
According to the C# Version 2.0 Language Specification, interface method
invocations on value types (uses a generics parameters) will not cause the value to
be boxed. This gave me the idea to use a value type for the calculator to avoid the
virtual function dispatch.
using System;
using System.Collections.Generic;
interface ICalculator<T>
{
T Add(T t1, T t2);
}
struct IntCalculator : ICalculator<int>
{
public int Add(int t1, int t2)
{
return t1
+ t2;
}
}
class AlgorithmLibrary<C,
T>
where C
: ICalculator<T>
{
static C
calculator = C.default;
public static T
Sum(List<T>
items)
{
T sum = T.default;
for(int i
= 0; i < items.Count; i++)
{
sum = calculator.Add(sum, items[i]);
}
return sum;
}
}
public class Class4
{
static void Main()
{
List<int>
foo = new List <int>();
foo.Add(1);
foo.Add(2);
foo.Add(3);
int sum = AlgorithmLibrary<IntCalculator, int>.Sum(foo);
Console.WriteLine(sum);
}
}
Depending on how the JIT decides to compile this, this could be very efficient (the
JIT could decide to generate specialized x86 code for every type that Sum() is used
on).