The sequence number in RenderTreeBuilder methods

Razor Components are normally used like HTML tags placed in .razor files, but they can also be built manually in C# code through a RenderTreeBuilder class. The RenderTreeBuilder class has methods like OpenComponent, OpenElement, AddAttribute that help you do that. Chris Sainty has an example on how to use RenderTreeBuilder and some of its methods to manually build components.

All the methods just mentioned on the RenderTreeBuilder take in a sequence number as its first parameter. For example, here is the signature of OpenComponent. 

// Summary:
//     Appends a frame representing a child component.
// Parameters:
//   sequence:
//     An integer that represents the position of the instruction in the source code.
//   componentType:
//     The type of the child component.
public void OpenComponent(int sequence, Type componentType);

Ideally I should hard-code this sequence number, Steve Sanderson has a gist that explains why you want to hard-code them and not generate them programmatically. Basically, the sequence number is used by Blazor to perform a diff of what's changed in the component tree, when used correctly it helps to speed up that diff. If you have if statements around tree building logic, and if you use a variable to store the sequence number and increase the variable programmatically each time you use it, you could potentially get different output each time and thus not helping the diff to be performant. 

A few important things Steve points out in his post

The diffing algorithm only cares that they should be an increasing sequence. It doesn't matter what initial value they start from, or whether there are gaps. One legitimate option would be to use the code line number as the sequence number. Or start from zero and increase by ones or hundreds or whatever interval you like.

I use the OpenComponent method to load plugin components dynamically in my Blazor application. I have a loop on all active plugins in the system set by the user and one by one load them dynamically. So, I find it difficult to achieve a hard-coded sequence number, but the good news is that plugins once configured they rarely change.