What I want to do is:
bool Convert( out Object output, Object source)
{
// find type of output.
// convert source to that type if possible
// store result in output.
return success
}
Is it possible?
Obviously, there is a brute force massive "if" construct that could work, but that would require writing an if block for every conceivable data type. Even assuming we'll limit it to primitives and strings, it's still a huge chunk of code. I'm thinking about something a bit more reflective.
Aside: While going through the api, I came across the Convert.IsDBNull() method, which will save me a lot of
if ( !databasefield.GetType().Equals( DBNull.Value ) )
Why in the name of G-d is it in Convert? Why not DBNull.IsDBNull() ?
Here is a sample that I use, you can inject other complex conversions into it by registering other type converters.
public static class Converter
{
public static T Convert<T>(object obj, T defaultValue)
{
if (obj != null)
{
if (obj is T)
{
return (T)obj;
}
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
if (converter.CanConvertFrom(obj.GetType()))
{
return (T)converter.ConvertFrom(obj);
}
}
return defaultValue;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With