Well, you could automate it with reflection and generics, but IMO overloads are the better choice - very much like your existing code.
Reflection / generics example - although I don't really recommend this route:
static void Main()
{
byte[] bytes = GetBytes(123);
}
static byte[] GetBytes<T>(T value) {
return Cache<T>.func(value);
}
static class Cache<T> {
public static readonly Func<T, byte[]> func;
static Cache() {
MethodInfo method = typeof(BitConverter)
.GetMethod("GetBytes", new Type[] { typeof(T) });
if (method == null) {
func = delegate { throw new ArgumentException(
"No GetBytes implementation for " + typeof(T).Name); };
} else {
func = (Func<T, byte[]>)Delegate.CreateDelegate(
typeof(Func<T, byte[]>), method);
}
}
}
You would then mix that with an AddData<T>
generic method that calls GetBytes<T>
etc.