Nerdy tidbits from my life as a software engineer

Friday, March 6, 2009

A Very Useful Extension Method

I’m working on a little project that requires a lot of dynamic type conversion.  So all over the place I have code that does:

public T DoSomething()
{  
  ...
  return (T)Convert.ChangeType(GetSomeValue(), typeof(T), CultureInfo.InvariantCulture))
}

When it occurred to me that I can save myself a lot of headaches and hassle with the help of a super-simple extension method called ConvertTo<T>:

/// <summary>
/// Attempts to convert an object into another type.
/// </summary>
/// <typeparam name="T">The type to convert to</typeparam>
/// <param name="originalType">The original object before it's converted</param>
/// <returns>An instance or value of T</returns>
public static T ConvertTo<T>(this object originalType)
{
    return (T)Convert.ChangeType(originalType, typeof(T), CultureInfo.InvariantCulture));
}

So that now I can just write:

public T DoSomething()
{
  ...
  return GetSomeValue().ConvertTo<T>();
}

Which is a lot simpler, and much more convenient.  Why didn’t I think of that earlier?

0 comments: