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.
T Add(T t1, T t2);
struct IntCalculator : ICalculator<int>
public int Add(int t1, int t2)
calculator = C.default;
public static T
T sum = T.default;
= 0; i < items.Count; i++)
sum = calculator.Add(sum, items[i]);
public class Class4
static void Main()
foo = new List <int>();
int sum = AlgorithmLibrary<IntCalculator, int>.Sum(foo);
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
I apologize for the lameness of this, but the comment spam was driving me nuts.
In order to be able to post a comment, you need to answer a simple question. Hopefully this question
is easy enough not to annoy serious commenters, but hard enough to keep the spammers away.
Anti-Spam Question: What method on java.lang.System returns an object's original hashcode (i.e. the
one that would be returned by java.lang.Object.hashCode() if it wasn't overridden)? (case is significant)
Powered by: newtelligence dasBlog 2.3.12105.0
© Copyright 2017, Jeroen Frijters