0

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.

bubbleking
  • 3,329
  • 3
  • 29
  • 49
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

1 Answers1

1

Along the lines of another question's answer, you can accomplish this using Convert.ChangeType() method.

public static T Get<T>(this String self)
{
  return (T)Convert.ChangeType(self, typeof(T));
}

Or even more sophisticated version with a fallback in case the conversion fails.

public static T Get<T>(this String self, T fallBack = default(T))
{
  try { return (T)Convert.ChangeType(self, typeof(T)); }
  catch { return fallBack; }
}

The usage is then as follows.

String source = ...
Guid guid = source.Get<Guid>();
int number = source.Get<int>(42);
Community
  • 1
  • 1
wentimo
  • 471
  • 3
  • 12
  • I took the liberty to adapt a bit to this case. Hope you like it. Also, you might want to remove the comment now. – Konrad Viltersten Dec 24 '15 at 19:41
  • Apparently, I forgot to check your answer as accepted. My bad. Better late than never, I guess. You should have reminded. The voting system is vital for quality assurance, even if one feels like a nagging looser reminding of voting. Which brings me to my part of it - don't forget to vote up if you've found the question to be interesting and rewarding. – Konrad Viltersten Jul 11 '20 at 09:37