0

I have a problem with the OutArgument of an activity. Here is a simplified code example:

    public class Animal
    {
    }

    public class Dog : Animal
    {
    }

    public class CreateNewDogActivity : CodeActivity<Dog>
    {
        protected override Dog Execute( CodeActivityContext context )
        {
            return new Dog();
        }
    }

    public class Program
    {
        public void Start()
        {
            Variable<Animal> animal = new Variable<Animal>( "animal" );

            var createDogStep = new FlowStep
            {
                Action = new CreateNewDogActivity()
                {
                    Result = new OutArgument<Dog>( animal )
                }
            };

            var flowChart = new Flowchart()
            {
                Variables = { animal },
                StartNode = createDogStep,
                Nodes = {
                    createDogStep
                }
            };

            WorkflowInvoker.Invoke( flowChart );
        }
    }

At runtime I get the following error:

Test method UnitTests.Base.Mvc.Workflow.OutArgumentTest.OutArgumentProgramTest threw exception: System.Activities.InvalidWorkflowException: The following errors were encountered while processing the workflow tree: 'VariableReference': Variable 'System.Activities.Variable`1[UnitTests.Base.Mvc.Workflow.Animal]' cannot be used in an expression of type 'UnitTests.Base.Mvc.Workflow.Dog', since it is of type 'UnitTests.Base.Mvc.Workflow.Animal' which is not compatible.

What is the easiest way to assign the Result-OutArgument of type "Dog" to a variable of type "Animal"?

Thank you!

1 Answers1

0

When the variable Animal was declared, it's type was set as Variable of type Animal. However, when you declared the OutArgument of type Dog, you passed into it an animal. This failed because Variable of animals are not compatible with Variable of dog and Generics are ensuring type safety. For further reading, look into covariance and contravariance

A workaround would be the following.

FlowStep createDogStep;
var doggy = animal as Variable<Dog>;
if (doggy != null) {
    createDogStep = new FlowStep {
        Action = new CreateNewDogActivity()
        {
            Result = new OutArgument<Dog>( doggy )
        }
};
Paul Tsai
  • 893
  • 6
  • 16