Search code examples
c#workflow-foundationworkflow-foundation-4

How to create a new InArgument<T> where the T can be changed dynamically


In a rehost WorkflowDesigner, I want to assign a valiable to InArguments by following code:

 Type inActivityType = leftActivity.GetType();
 PropertyInfo inPropInfo = inActivityType.GetProperty(inArgumentName);
 InPropInfo.SetValue(leftActivity, 
                     new InArgument<someType>(new VisualBasicValue<someType>(variableName)), 
                     null);

Since the "someType" is assigned with different type dynamically, the regular way to create a new InArgument will not working. One idea I found is:

//  Type theType - the value of theType will be assigned dynamicly, 
//  base on different InArgument be selected

 Type InArgType = typeof(InArgument<>).MakeGenericType(new[] { theType });
 object InArg = Activator.CreateInstance(InArgType);
.  .  .
  InPropInfo.SetValue(leftActivity, 
                     InArg, 
                     null);

But the problem is, I can only create a new InArgument, but can not assign new VisualBasicValue(variableName) to it.

Thanks for any idea.


Solution

  • You could use the same trick to create a new instance of VisualBasicValue, too, and pass that along to InArgument using the overload of CreateInstance that takes constructor arguments. Perhaps something like this:

    Type InArgType = typeof(InArgument<>).MakeGenericType(new[] { theType });
    Type vbValueType = typeof (VisualBasicValue<>).MakeGenericType(new[] {theType});
    object vbValue = Activator.CreateInstance(vbValueType, variableName);
    object InArg = Activator.CreateInstance(InArgType, vbValue); 
    

    However, depending on what you are tring to do, you could just use the non-generic InArgument instead and not worry about generics there.