Share via


Providing a default value for an InArgument (WF)

If an activity wishes to provide a default value for an InArgument that will be used in case it is not supplied, it will need to be provided programmatically after checking the execution context for the value, rather than using DefaultValueAttribute or setting the value during activity initialization.

DefaultValueAttribute cannot be used for this purpose, since it is intended to be used to streamline serialization by not serializing values that match the default. Neither the workflow designer nor the workflow runtime checks the value given by DefaultValueAttribute, since this is not the intended purpose of the attribute, and the reflection involved would create an unacceptable performance hit.

The following attribute will not provide a default value to either the runtime or the designer:

[DefaultValue("Enter default text here")]
public InArgument<string> Text { get; set; }

Since at runtime, the value for the argument is obtained from the execution context, the following code will supply a default value for the argument in the workflow designer, but not during runtime. That is, if the default value supplied by the designer is deleted in the Properties window, the value at runtime will be the new (null) value, rather than the initialized value. However, if the activity is created in code without using the designer, the default value will be applied.

private InArgument<string> textValue = "Enter text here";
public InArgument<string> Text
{
    get { return this.textValue; }
    set { this.textValue = value; }
}

In order to provide a default value for the attribute to the runtime if it is not specified in the designer (that is, if it is left as null in the designer), it must be supplied programmatically after first checking the execution context:

protected override void Execute(CodeActivityContext context)
{
    // Obtain the runtime value of the Text input argument
    string text = context.GetValue(this.Text);
    if (text == null)
        text = "No text supplied.";
    Console.WriteLine(text);
}