locked
Expression.Call doesn't do boxing? RRS feed

  • Question

  • I noticed that Expression.Call throws exception instead of doing boxing, as opposed to regular C# (IL?) calls. See the following code snippet and especially the comments inside:

     

    Code Snippet

    public static void PrintObject(Object obj) {

       Console.WriteLine(obj.ToString());

    }

     

    delegate void Func();

     

    static void Main(string[] args) {

    //

    // This one works well and no explicit conversion/boxing needed

    //

    Func lambda = () => PrintObject(5);

    lambda.DynamicInvoke();

     

    var method = typeof(Program).GetMethod("PrintObject");

    //

    // ArgumentException: Expression of type 'System.Int32' cannot

    // be used for parameter of type 'System.Object'

    // of method 'Void PrintObject(System.Object)'

    //

    var call1 = Expression.Call(method, Expression.Constant(5));

    //

    // This one works well, but produces more complex and

    // therefore slower expression tree: () => PrintObject(Convert(5))

    //

    var call2 = Expression.Call(method,

                   Expression.Convert(

                     Expression.Constant(5),

                     typeof(object)

    )

      );

    var xlambda = Expression.Lambda(call2);

    xlambda.Compile().DynamicInvoke();

    }

     

     

    I'm writing a generic expression parser. So now I should check every Call node, and every parameter in the call, in order to add the Convert node in case the expected type is Object and the actual type is a ValueType. Isn't it too much? Is this a bug or I'm missing something?

     

    Thanks,

      Boris.

     

    Tuesday, March 18, 2008 3:01 PM

Answers

  • There is no automatic boxing but this should work:

     

    Code Snippet

    var call1 = Expression.Call(method, Expression.Constant(5, typeof(object)));

     

     

    Petar

    Tuesday, March 18, 2008 9:39 PM

All replies

  • There is no automatic boxing but this should work:

     

    Code Snippet

    var call1 = Expression.Call(method, Expression.Constant(5, typeof(object)));

     

     

    Petar

    Tuesday, March 18, 2008 9:39 PM
  • Works like a charm! Thanks a lot.

     

    Tuesday, March 18, 2008 10:34 PM
  • You are welcome.

     

    P

     

    Tuesday, March 18, 2008 10:38 PM