Converting string to a simple type

Posted by zespri on Stack Overflow See other posts from Stack Overflow or by zespri
Published on 2010-05-21T03:52:29Z Indexed on 2010/05/21 4:00 UTC
Read the original article Hit count: 225

Filed under:
|
|
|

.Net framework contains a great class named Convert that allows conversion between simple types, DateTime type and String type. Also the class support conversion of the types implementing IConvertible interface.

The class has been implemented in the very first version of .Net framework. There were a few things in the first .Net framework that were not done quite right. For example .Parse methods on simple types would throw an exception if the string couldn't be parsed and there would be no way to check if exception is going to be thrown in advance.

A future version of .Net Framework removed this deficiency by introducing the TryParse method that resolved this problem.

The Convert class dates back to time of the old Parse method, so the ChangeType method on this class in implemented old style - if conversion can't be performed an exception is thrown.

Take a look at the following code:

public static T ConvertString<T>(string s, T @default)
{
    try
    {
        return (T)Convert.ChangeType(s, typeof(T), CultureInfo.InvariantCulture);
    }
    catch (Exception)
    {
        return @default;
    }            
}

This code basically does what I want. However I would pretty much like to avoid the ugly try/catch here. I'm sure, that similar to TryParse, there is a modern method of rewriting this code without the catch-all. Could you suggest one?

© Stack Overflow or respective owner

Related posts about c#

Related posts about types