I am trying to write a generic Parse method that converts and returns a strongly typed value from a NamedValueCollection. I tried two methods but both of these methods are goin
For better readability, you could use a generic dictionary with an anonymous function as follows:
var parserFuncs = new Dictionary>() {
{ typeof(int), p => (int) int.Parse(p) },
{ typeof(bool), p => (bool) bool.Parse(p) },
{ typeof(long), p => (long) long.Parse(p) },
{ typeof(short), p => (short) short.Parse(p) },
{ typeof(DateTime), p => (DateTime) DateTime.Parse(p) }
/* ...same for all the other primitive types */
};
return (T) parserFuncs[typeof(T)](value);