How/when BizTalk initializes variables used in Expression shape

I just learned something new the other day about how BizTalk initializes variables that is used in Expression shapes. I have always since my tests with BizTalk 2004 betas performed explicit new of variables that I have declared, i.e. I have called a constructor using new SomeType(). However, I just learned from a member of my current project team that if I only intend to use the default constructor I don't have to do new in the Expression shape.

The discussion came up as I have created new constructor for a utility class he was using. The new constructor took a parameter and he asked me if I knew how to provide that paramteter in the declaration (in the scope in the Orchestration View). My reply was: "What, don't you do new in the Expression shape?!"

As I might not be the only one who have missed this convenient feature I though I would share it here.

But to make it more interesting I performed some small tests to understand when the default constructor is called. I used a simple orchestration with a Receive and an Expression shape and a test class with traces in the constructor, and did three tests:

Trace.WriteLine(“Start of expr”);var.X();

Trace.WriteLine(“Start of expr”);var = new SomeType(“test”);var.X();

Trace.WriteLine(“Start of expr”);var = new SomeType();var.X();

The result of these tests were:

SomeType()Start of exprX()

SomeType()Start of exprSomeType(string s)X()

SomeType()Start of exprSomeType()X()

What this shows is that the default constructor is ALWAYS called, and it is actually called before first usage of the variable which is a bit surprising. If automatic instances are created I would have expected them to appear immediately before using the variable that needs an instance of the class. You can also notice that in cases where you actually call a constructor explicitly from the code you will execute the constructor twice.

[UPDATE]:
You can avoid calling the default constructor by setting the Use Default Constructor property to false, this is a property on the variable in the Orchestration View. The default value of this property is true, so by default the default constructor will be called.

Conclusion:

  • Don’t initialize variables in code if you only intend to use the default constructor.
  • If using non-default constructors it is recommended to set the Use Default Constructor property to false. This is especially true if the class you are using has an “expensive” default constructor.
  • Using a non-default constructor and not setting Use Default Constructor to false incurs a performance impact as you always will run both the default constructor and the non-default constructor.

[UPDATE 2006-08-01]: Added text about Use Default Constructor. Thank your Jonas for pointing this out!