Skip to content

Instantly share code, notes, and snippets.

@caleblloyd
Created October 26, 2016 19:47
Show Gist options
  • Save caleblloyd/1659b365fc86acd774ce7034400b05ce to your computer and use it in GitHub Desktop.
Save caleblloyd/1659b365fc86acd774ce7034400b05ce to your computer and use it in GitHub Desktop.
public override T GetFieldValue<T>(int ordinal)
{
try
{
return base.GetFieldValue<T>(ordinal);
}
catch (InvalidCastException e)
{
return ConvertWithReflection<T>(ordinal, e);
}
}
public override async Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken)
{
try
{
return await base.GetFieldValueAsync<T>(ordinal, cancellationToken).ConfigureAwait(false);
}
catch (InvalidCastException e)
{
return ConvertWithReflection<T>(ordinal, e);
}
}
private T ConvertWithReflection<T>(int ordinal, InvalidCastException e)
{
try
{
// try casting using reflection
var dataParam = Expression.Parameter(typeof(string), "data");
var body = Expression.Block(Expression.Convert(dataParam, typeof(T)));
var run = Expression.Lambda(body, dataParam).Compile();
return (T) run.DynamicInvoke(GetReader().GetValue(ordinal));
}
catch (Exception)
{
// throw original InvalidCastException
throw e;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment