Skip to content
June 25, 2013 / windperson

Generic ADO.net “weak type” datarow value converter

A simple “weak type” datarow value converter that convert datacolumn value of a datarow to basic value type or nullable type is as follows:

T ConvertToTypeData<T>(DataRow dr, String columnName, T defaultValue = default(T))
{
    var retValue = defaultValue;

    Type toType = typeof(T);
    if (dr.IsNull(columnName))
    {
        if (Nullable.GetUnderlyingType(toType) != null)
        {
            retValue = default(T);
        }
    }
    else
    {
        var data = dr[columnName];
        Type dataType = data.GetType();

        if (dataType.IsCastableTo(toType))
        {
            retValue = (T)data;
        }
        else
        {
            // try to create return type object from given dataType value.
            ConstructorInfo ctorInfo = toType.GetConstructor(new[] { dataType });
            if (ctorInfo != null)
            {
                retValue = (T)ctorInfo.Invoke(new[] { data });
            }
            //extract string 1st char if fromType is string and toType is char or nullable char
            else if (data is string && !String.IsNullOrEmpty(data.ToString()) && (toType == typeof(char) || toType == typeof(char?)))
            {
                var charValue = data.ToString().ToCharArray(0, 1)[0];
                if (toType == typeof(char?))
                {
                    TypeConverter conv = TypeDescriptor.GetConverter(toType);
                    retValue = (T)conv.ConvertFrom(charValue);
                }
                else
                {
                    retValue = (T)Convert.ChangeType(charValue, toType);
                }
            }
            else
            {
                //last resort
                retValue = (T)Convert.ChangeType(data, toType);
            }
        }
    }
    return retValue;
}

and it use a helper class extension method provided in a stackoverflow discussion:
http://stackoverflow.com/a/2224421

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: