Why is this a compile time error?
public TCastTo CastMe(TSource i)
{
return (TCastTo)i;
}
Error:
C# uses one cast syntax for multiple different underlying operations:
In generic context, the compiler has no way of knowing which of those is correct, and they all generate different MSIL, so it bails out.
By writing return (TCastTo)(object)i; instead, you force the compiler to do an upcast to object, followed by a downcast to TCastTo. The compiler will generate code, but if that wasn't the right way to convert the types in question, you'll get a runtime error.
Code Sample:
public static class DefaultConverter
{
private static Converter cached;
static DefaultConverter()
{
ParameterExpression p = Expression.Parameter(typeof(TSource));
cached = Expression.Lambda(Expression.Convert(p, typeof(TCastTo), p).Compile();
}
public static Converter Instance { return cached; }
}
public static class DefaultConverter
{
public static TOutput ConvertBen(TInput from) { return DefaultConverter.Instance.Invoke(from); }
public static TOutput ConvertEric(dynamic from) { return from; }
}
Eric's way sure is shorter, but I think mine should be faster.