About type coercion

The hosted compiler does something called type coercion. It converts one type to another type using the widening and narrowing conversions specified by the big VB compiler. On the whole, this is very useful functionality. It allows you to strongly type your arguments but still set your Int16 variable to 5 or your string variable to Nothing.

Type coercion is especially important for delegate types and lambda expressions. When the compiler encounters a lambda expression, it infers its type as an anonymous delegate type. The compiler is not smart enough to coerce anonymous delegate types to something serializable, like Func<Boolean>, without a hint.  It’s up to the activity author to provide the type to the compiler. Here is a quick demonstration of what happens if you omit the type. Create an activity with an untyped argument. Create an activity designer with an untyped ExpressionTextBox. Drop the activity into a workflow, and in the ETB, set its expression to Function() true. Save. Observe the following on reload:

System.Xaml.XamlObjectReaderException: Type 'System.Activities.InArgument`1[[VB$AnonymousDelegate_0`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], $HostedHelperAssembly$, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]' not visible. If the type is local, please set the LocalAssembly field in XamlReaderSettings.

If you specify the type of the argument supplied here, you wouldn’t have a problem. The compiler would coerce the anonymous delegate type to a Func<Boolean> for you. This is one reason I recommended always typing your arguments in my previous post on untyped arguments.

Type coercion is not supported for VisualBasicReference expressions. Here is a simple demonstration of what happens if you try to coerce the type. Create an activity with an OutArgument<object>. Create an activity designer with an ETB, setting the UseLocationExpression attribute to true. Now drop the activity put a string variable named variable1 in its corresponding ETB. Observe the following compiler error:

Error    1    Compiler error(s) encountered processing expression "variable1".Invalid L-value expression.:Reference expressions cannot end with Conversion. The provided expression's type must exactly match the type T of VisualBasicReference<T> or LambdaReference<T>.

This conversion works just fine for InArguments (VisualBasicValue expressions).