Skip to content

Instantly share code, notes, and snippets.

@badcommandorfilename
Created June 29, 2018 00:57
Show Gist options
  • Save badcommandorfilename/86f19bb5865da5f56b56ea778e1a7af8 to your computer and use it in GitHub Desktop.
Save badcommandorfilename/86f19bb5865da5f56b56ea778e1a7af8 to your computer and use it in GitHub Desktop.
C# Runtime type Cast and CastEnumerable
static IEnumerable CastEnumerable(IEnumerable<object> input, Type t)
{
foreach(var o in input)
{
yield return Cast(o, t);
}
}
static object Cast(object obj, Type t)
{
try
{
var param = Expression.Parameter(obj.GetType());
return Expression.Lambda(Expression.Convert(param, t), param)
.Compile().DynamicInvoke(obj);
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment