Skip to content

Instantly share code, notes, and snippets.

@duncansmart
Created January 24, 2012 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duncansmart/1670953 to your computer and use it in GitHub Desktop.
Save duncansmart/1670953 to your computer and use it in GitHub Desktop.
Returns, and converts as appropriate, the value of the supplied data record (DataReader) that corresponds with the named column
internal static class DataReaderUtil
{
public static T GetValue<T>(this IDataRecord record, string columnName)
{
T result = default(T);
int ordinal = record.GetOrdinal(columnName);
if (record.IsDBNull(ordinal))
return result;
Type targetType = typeof(T);
// Convert.ChangeType() can't handle Enums
if (result is Enum)
{
targetType = typeof(int);
}
// Nullable? Convert.ChangeType() can't handle those either...
else if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
targetType = targetType.GetGenericArguments().First();
}
try
{
result = (T)Convert.ChangeType(record.GetValue(ordinal), targetType);
}
catch (FormatException ex)
{
throw new FormatException(string.Format("Error converting {0} to {1}.", columnName, targetType), ex);
}
catch (InvalidCastException ex)
{
throw new FormatException(string.Format("Error converting {0} to {1}.", columnName, targetType), ex);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment