0

I need to be able to get the type from the currentStep variable and use that type for the newExpression assignment. What this code is doing is changing the Expression out type. Is there a way where I can dynamically set the newExpression func out type based on the currentStep type?

PropertyInfo currentStep = wizardTransaction.GetCurrentStepPropertyInfo();

string currentStepName = wizardTransaction.GetCurrentStepPropertyInfo().PropertyType.Name;

var body = Expression.Property(expression.Body, currentStepName);

var newExpression = Expression.Lambda<Func<TModel, **currentStep.GetType()**>>(body, expression.Parameters[0]);

var model = ModelMetadata.FromLambdaExpression(newExpression, helper.ViewData).Model;

The method which the above code is in is a static class so the answer thats the solution that this is marked as a duplicate for does not apply as the this keyword used in the accepted answer cant not be used in a static class.

Bad Dub
  • 1,503
  • 2
  • 22
  • 52
  • 1
    Possible duplicate of [How do I use reflection to call a generic method?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – thehennyy Oct 10 '18 at 11:31
  • I can't use that solution as it states to use generic.Invoke(this, null); But my class is static so the this keyword can not be used. – Bad Dub Oct 10 '18 at 11:34
  • Pass null for the object-instance parameter if you want to call a static method. – thehennyy Oct 10 '18 at 11:37
  • So how do I incorporate their answer with mine? I need to use the type against my newExpression Expression. – Bad Dub Oct 10 '18 at 11:39
  • @BadDub You do not need to use `this` to call `Invoke`. Also, there are `Expression.Lambda` that accept delegate type as normal parameter, but not as generic argument. – user4003407 Oct 10 '18 at 11:40
  • Checking out the Expression.Lambda now. Will let you know how I get on. – Bad Dub Oct 10 '18 at 11:42
  • @PetSerAl when I use the Expression.Lamda you were talking about the next line 'ModelMetadata.FromLambdaExpression(newExpression, helper.ViewData).Model;' fails as I now have to provide that with the types. – Bad Dub Oct 10 '18 at 11:44
  • Then provide these types? – thehennyy Oct 10 '18 at 11:47
  • But its the same problem as the original question. I'm just moving the problem down one line. – Bad Dub Oct 10 '18 at 11:48
  • 1
    Thats what you have to life with when using reflection. reflection trades type-safetyness for flexibility. – thehennyy Oct 10 '18 at 12:33

0 Answers0