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.