I really wish there were more guidance on how to handle static reflection situations. Some kind of helper library would be nice. I’m actually surprised one doesn’t exist given its usefulness and the quirks involved. Consider this scenario – you’re reflecting over the details of a method call and the parameters passed. You actually care about the values that have been passed. How do you discover them?
It goes something like this, I think:
If you don’t explicitly convert the value type to an object, you’ll get an exception that will confuse you (something to the effect of “Expression of type 'System.Decimal' cannot be used for return type 'System.Object'”). It’s confusing because, c’mon, isn’t everything a System.Object? If a function returns object, can’t you return anything? Well, no. And I’m guessing from what Eric Lippert also says here, baking the conversion rules for C# (in this case, that almost everything is convertible to object and so C# does it implicitly) or VB or any other .NET language into LINQ would be doing a disservice to the other languages.
It goes something like this, I think:
var argument = GetExpression(); if (argument.Type.IsValueType) { argument = Expression.Convert(argument, typeof(object)); } var getValueExpression = Expression.Lambda<Func<object>>(argument); var getValue = getValueExpression.Compile(); var value = getValue();I found that here.
If you don’t explicitly convert the value type to an object, you’ll get an exception that will confuse you (something to the effect of “Expression of type 'System.Decimal' cannot be used for return type 'System.Object'”). It’s confusing because, c’mon, isn’t everything a System.Object? If a function returns object, can’t you return anything? Well, no. And I’m guessing from what Eric Lippert also says here, baking the conversion rules for C# (in this case, that almost everything is convertible to object and so C# does it implicitly) or VB or any other .NET language into LINQ would be doing a disservice to the other languages.
Comments