0

I have a string and i wanted to convert that string into specified type. However before the actual conversion happens i also want to check if i can convert the value to destination type.

I have generic extension method which does the conversion

public static class StringExtensions
{
    public static TDest ConvertStringTo<TDest>(this string src)
    {
        if (src == null)
        {
            return default(TDest);
        }           

        return ChangeType<TDest>(src);
    }

    private static T ChangeType<T>(string value)
    {
        var t = typeof(T);                                    
        if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {   
            t = Nullable.GetUnderlyingType(t);
        }

        return (T)Convert.ChangeType(value, t);
    }
}

the above method will work as long as the source string is valid. However if the source string invalid i get exception. For example

 var source = "this is integer";
 source.ConvertStringTo<int?>();

this would throw exception

Input string was not in a correct format.

 var source = "12/32/2015";
 source.ConvertStringTo<DateTime?>();

this would throw exception

String was not recognized as a valid DateTime.

I wanted to return default(T) if method is unable convert the value. I know i can do that by adding try catch but i was looking for a solution without adding try catch.

Note
I have gone through SO post here but the answer only checks for null.
Also i m using .Net Core.

Community
  • 1
  • 1
LP13
  • 30,567
  • 53
  • 217
  • 400
  • Better you use TryParse,although there will be multiple if else otherwise it will be very slow and you need to write complex code. – Vivek Nuna Nov 17 '16 at 20:44
  • The example with a number shows that it may be difficult to do this without throwing and catching exceptions. It may be better to create range of extension methods like `.ToInt()`, `.ISODateStringToDateTime()` etc. – csharpfolk Nov 17 '16 at 21:00

0 Answers0