none
Accessing ParameterExpression from Expression.New RRS feed

  • Question

  • Hello,

    So here's what my code currently looks like:

     

    User u = new User();
    u.Name = "Test User";
    
    Type propertyType = u.GetType().GetProperty("Name").DeclaringType;
          
    ParameterExpression instance = Expression.Parameter(propertyType);
    
    User newUser = Expression.Lambda<Func<Type, object>>
     (Expression.New(instance.Type), new ParameterExpression[] { instance })
      .Compile().Invoke(propertyType) as User;
    

     


    And here's the error I'm getting:

    ParameterExpression of type 'ConsoleApplication1.User' cannot be used for delegate parameter of type 'System.Type'

    What I want to do is create a new instance of propertyType but I can't seem to get past this error.  I'm pretty sure that it is something very simple that I'm missing but I don't know what that is.  Does anyone know what I'm doing wrong?

    This part will be integrated with another part that does a loop through all the properties in an unknown object.  That's why I'm doing the reflection and assigning the DeclaringType to propertyType - I'm matching what my real world app will do.

    Thanks,
    Corey

    Friday, July 22, 2011 3:04 PM

Answers

  • I figured it out.  Now my code looks like this:

    User u = new User();
    u.Name = "Test User";
    
    Type propertyType = u.GetType().GetProperty("Name").DeclaringType;
    
    User newUser = Expression.Lambda<Func<object>>
     (Expression.New(propertyType))
     .Compile().Invoke() as User;
    

    • Marked as answer by da.3vil.droid Friday, July 22, 2011 3:35 PM
    Friday, July 22, 2011 3:35 PM

All replies

  • I figured it out.  Now my code looks like this:

    User u = new User();
    u.Name = "Test User";
    
    Type propertyType = u.GetType().GetProperty("Name").DeclaringType;
    
    User newUser = Expression.Lambda<Func<object>>
     (Expression.New(propertyType))
     .Compile().Invoke() as User;
    

    • Marked as answer by da.3vil.droid Friday, July 22, 2011 3:35 PM
    Friday, July 22, 2011 3:35 PM
  • If you're trying to create an instance of a type (that you hope inherits from User) but is not known until runtime:

    User newUser = Activator.CreateInstance(propertyType) as User;

    Constructing a lambda and compiling it and invoking it is overkill.

     



    Friday, July 22, 2011 3:59 PM
  • I was originally using Activaotr.CreateInstance but then came across several articles that stated the compiled lambda is much, much faster.  Also, Invoke isn't being called in my code; I just had it there to test something.
    Friday, July 22, 2011 8:17 PM