Proper use of sequence parameter in loops

Viewed 133

This post indicates I should be using hard coded values. However it does not spell out how to deal with loops. What is the correct way? Does using builder.SetKey(model); circumnavigate the problem? The code is working without issue. I just want to clear this up before making a repo public for this NuGet package

        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {

            ...

            int i = 3;
            foreach (object model in models)
            {
                (Type componentType, string propertyName) viewComponentInfo = GetModelViewComponentInfo(model);

                Type componentType = viewComponentInfo.componentType;
                if (componentType is not null)
                {
                    string propertyName = string.IsNullOrWhiteSpace(viewComponentInfo.propertyName) ? "Model" : viewComponentInfo.propertyName;
                    builder.OpenComponent(i++, componentType);
                    builder.AddAttribute(i++, propertyName, model);
                    builder.SetKey(model);
                    builder.CloseComponent();
                }
            }
            ...
        }

1 Answers

You are doing exactly what that post says you should not.

To quote the page you linked to:

Q: Despite this, I still want to generate the sequence numbers dynamically. Can I?
A: You can, but it will make your app performance worse.

The advice tells you to use:

// int i = 3;

foreach(...)
{
   ...
   builder.OpenComponent(3, componentType);
   builder.AddAttribute(4, propertyName, model);
   builder.SetKey(model);
}

A little counter intuitive but the numbering is there to maintain information about loops and if/else branches. SetKey() helps to identify the iterations of the foreach loop.

As far as I can tell it will only matter if your models collection changes at runtime, I'm not sure if that's the case for your package.

But I would err on the safe side and manually number those lines.

Related