I am attempting to do some data conversion. Unfortunately, much of the data is in strings, where it should be int's or double, etc...
So what I've got is something like:
double? amount = Convert.ToDouble(strAmount);
The problem with this approach is if strAmount is empty, if it's empty I want it to amount to be null, so when I add it into the database the column will be null. So I ended up writing this:
double? amount = null;
if(strAmount.Trim().Length>0)
{
amount = Convert.ToDouble(strAmount);
}
Now this works fine, but I now have five lines of code instead of one. This makes things a little more difficult to read, especially when I have a large amount of columns to convert.
I thought I'd use an extension to the string class and generic's to pass in the type, this is because it could be a double, or an int, or a long. So I tried this:
public static class GenericExtension
{
public static Nullable<T> ConvertToNullable<T>(this string s, T type) where T: struct
{
if (s.Trim().Length > 0)
{
return (Nullable<T>)s;
}
return null;
}
}
But I get the error: Cannot convert type 'string' to 'T?'
Is there a way around this? I am not very familiar with creating methods using generics.
There is a generic solution (for any type). Usability is good, but implementation should be improved: http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/
This allows you to write very clean code like this:
and also:
My example for anonimous types:
Another thing to keep in mind is that the string itself might be null.
You could try using the below extension method:
This way you can do this:
Give this a shot...
Then call it like this...
Another variation. This one
NotSupportedException
if the type can not be converted fromstring
. For instance, a custom struct without a type converter.(T?)null
if the string fails to parse. No need to check for null or whitespace.