5

I'm using a DataTable and assigning columns different types. I have a scenario where I'm receiving String data and I want to parse it based on the column's assigned type, but I can't figure out how to get to the parse methods.

Is is it possible to access the Type instance's parse methods in a generic way?

Josh Russo
  • 3,080
  • 2
  • 41
  • 62

2 Answers2

5

You're looking for Convert.ChangeType.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Wow, I couldn't have received a faster response if you were standing next to me! LOL That's awesome. Thanks! – Josh Russo Dec 22 '10 at 14:17
2

If you are using anything more than basic types (that Convert.ChangeType handles quite nicely), the preferred way of doing this is via the TypeConverter:

var converter = TypeDescriptor.GetConverter(type);
object val = converter.ConvertFromString(s); // note various overloads,
                                             // or ConvertFromInvariantString

This is convenient because this model can be extended to recognise additional types (or change the implementation for existing types), both at compile-time (adding [TypeConverter(...)]) or at run-time (TypeDescriptor.AddAttributes(...)).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900