Use Insert <T> (T o) with Object Type
4 answers
You basically need to call it using reflection (e.g. using MethodInfo.MakeGenericMethod). Generics is type compilation type security, while you don’t know the type at compile time. Alternatively, you can use dynamic typing if you are in C # 4.
Using reflection is a pain in terms of:
- There is a lack of type safety during compilation, so errors can only be detected in tests (or in production!)
- Performance
- Ease of coding
# 4, :
dynamic d = x;
r.Insert(d);
+5
You need to invoke the Insert command with reflection to indicate the type at runtime.
I would add a second overload of the insert method, for example:
private static readonly MethodInfo setMethod = typeof(WhateverCIs).GetMethod("Set");
public void Insert(object o)
{
var t = o.GetType();
var set = setMethod.MakeGenericMethod(new[] { t });
(set.Invoke(c) as WhateverSetReturns).Add(o);
}
+1