I've used the following two extension methods for converting the incoming strings into what I need them to be. They are used on data that has been converted to strings, but where the original type is always known.
public static int ToInt(this string self)
{
try { return Convert.ToInt32(self); }
catch { return default(int); }
}
public static double ToInt(this string self)
{
try { return Convert.ToDouble(self); }
catch { return default(double); }
}
I just learned that the information flow is going to be extended and contain other types, as well. Adding a new extension method for each is a sure way to insanity in the long run, not to mention code redundancy. So I attempted to make it more general.
public static T ToType<T>(this string self)
{
if (typeof(T) == typeof(int))
try { return Convert.ToInt32(self); }
catch { return default(int); }
}
However, the compiler has issues with that (regarding type, of course). I've tried casting in the first return, and using the provided type in the second, but the issue still remains.
public static T ToType<T>(this string self)
{
if (typeof(T) == typeof(int))
try { return (T)Convert.ToInt32(self); }
catch { return default(T); }
}
Can it be done at all, or am I going to end up creating many similar extension methods? Please keep in mind that since I will always know what types are being served, I only need to cover those, in case a fully generic and type safe approach isn't possible, or is very cumbersome.
Also, please note that I had surgery yesterday, and I'm still a bit off, so the answer might be embarrassingly simple.