Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Convert.ChangeType() makes sense with a string value?

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?

like image 240
Koen Avatar asked Dec 16 '22 13:12

Koen


1 Answers

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);

--

like image 163
Stecya Avatar answered Jan 11 '23 22:01

Stecya