Why would this code complain about "the arity of the generic type definition"?
Figured it out.
I had DictionaryComparer
declared as an inner class. I can only assume that MakeGenericType
wanted to make a Query<T>.DictionaryComparer<string,object>
and was not provided T
.
Failing code
class Program
{
static void Main(string[] args)
{
var q = new Query<int>();
q.CreateError();
}
}
public class Query<TSource>
{
public Query()
{
}
public object CreateError()
{
Type def = typeof(DictionaryComparer<,>);
Type t = def.MakeGenericType(new Type[] { typeof(String), typeof(object) });
return Activator.CreateInstance(t);
}
class DictionaryComparer<TKey, TValue> : IEqualityComparer<IDictionary<TKey, TValue>>
{
public DictionaryComparer()
{
}
public bool Equals(IDictionary<TKey, TValue> x, IDictionary<TKey, TValue> y)
{
if (x.Count != y.Count)
return false;
return GetHashCode(x) == GetHashCode(y);
}
public int GetHashCode(IDictionary<TKey, TValue> obj)
{
int hash = 0;
unchecked
{
foreach (KeyValuePair<TKey, TValue> pair in obj)
{
int key = pair.Key.GetHashCode();
int value = pair.Value != null ? pair.Value.GetHashCode() : 0;
hash ^= key ^ value;
}
}
return hash;
}
}
}
CLR creates an internal data structure for each and every type in use by an application.These data structures are called type objects. A type with generic type parameters is called an open type, and the CLR does not allow any instance of an open type to be constructed (similar to how the CLR prevents an instance of an interface type from being constructed).
Change
Type t = def.MakeGenericType(new Type[] { typeof(String), typeof(object) });
on the
Type t = def.MakeGenericType(new Type[] { typeof(TSource), typeof(String), typeof(object) });