I noticed the following method while on a journey through reflector the other day.
RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter(Type otherType)
Quite an odd method really.
Example in use:
GenericEqualityComparer
CreateInstanceForAnotherGenericParameter(typeof(T));
This lets you make a GenericEqualityComparer<T> instance.
First thought is why wouldn’t you write
new GenericEqualityComparer<T>()
?
As it turns out its because GenericEqualityComparer has a restriction which says T : IEquatable and the current generic type calling this code has no restriction on T.
So this method is really useful. It allows you to write a set of if statements checking what T implements and then defer processing to appropriate special case generics.
Unfortunately the above method is internal, so you would have to do the equivelent with a bunch of reflection, probably a bit slower too.
I am thinking that we should petition Microsoft to provide a language construct which is syntactic sugar for this method.
var v = new GenericEqualityComparer<T>() : where T is IEquatable;
Could throw an InvalidOperationException if you haven’t guarded for the case where T is not IEquatable;
In other news 0.0.2.0 of TMD.Algo should be out soon, I have a dequeue, a couple more sorts (really basic ones) and an alternative Heap which supports O(1) Contains, and O(log n) Remove at the expense of some extra book keeping. Useful for implementing Prim’s algorithm as the key reduction step can be done in O (log n) (as needed) by simply removing the entry and adding the new one after changing the key.