Question

I found this great post by @hugoware about parsing values: http://hugoware.net/blog/more-control-when-parsing-values. I re-used his code sample in a project but now I noticed in the last block (line 154 of his code) he uses the Convert.ChangeType() method as a last attempt to "convert" the value.

Now I wonder if this makes sense, since we're always starting from a string value and I guess Convert.ChangeType only does casting on value types? Does it make sense to try that or will it always fail?

Was it helpful?

Solution

you can use Convert.ChangeType() with strings. See the MSDN documentation: ChangeType

From MSDN:

string s = "12/12/98";
DateTime dt = (DateTime)Convert.ChangeType(s, typeof(DateTime));

In the above case converting from a string makes sense.

By using this method I suppose it is possible to extend it even further to cope with non-string values e.g.

private static bool _PerformConvert<T,U>( U value, ref T result )
{
    object convert = Convert.ChangeType(value, typeof(U) );
    // Continue ...
}

It might make sense to be able to convert from any value around for example, if you had an interface to a 3rd party dll that provided a numerical representation of an object (it has happened!) you could use the more generic version of the code to convert between the 3rd party representation and another representation that makes more sense to your code.

OTHER TIPS

If you just want to convert strings, I advice you to use ConvertToString / ConvertFromString

 TypeConverter converter = TypeDescriptor.GetConverter(type);
 string res = converter.ConvertToString(obj);
 object original = converter.ConvertFromString(res);

--

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top