I'm trying to create an expression to convert some numeric values. Here is what I have tried:
public object ConvertValue(object value, Type targetType) {
var parameter = Expression.Parameter(typeof(object), "p"); // "p"
var convert = Expression.Convert(parameter, targetType); // Convert(p, Int64)
var targetConvert = Expression.Convert(convert, typeof(object)); // Convert(Convert(p, Int64), Object)
var lambda = Expression.Lambda<Func<object,object>>(targetConvert, parameter); // p => Convert(Convert(p, Int64), Object)
var method = lambda.Compile();
var result = method(value); // HERE I GET THE ERROR!
return result;
}
But when I call it, as this simple test:
[Fact]
public void TestConvert() {
var result = ConvertValue(23, typeof(long));
Assert.Equal(typeof(long), result.GetType());
}
I get the error:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int64'.
at lambda_method(Closure , Object ) bla bla bla...
Any idea what's happening here and what Int32 cannot be cast to Int64? Thanks in advance.
stringtoint. What usually happens is that what looks like a cast in C# can be any of the following things: A type-cast, an invocation of an explicit conversion operator (which is what happens with numeric conversions like "casting"inttolong), boxing a value type, or unboxing a value type. It can be a bit confusing that all those things share the same syntax. - JoeyConvert.ChangeTypemethod? - D Stanley