When to use MergeAttribute over Attributes.Add

3.3k views Asked by At

When using TagBuilder one can use TagBuilder.Attributes.Add(..) or TagBuilder. MergeAttribute(..) to add attributes to the HTML element under construction:

TagBuilder formBuilder = new TagBuilder("form");
formBuilder.Attributes.Add("method", "get");
formBuilder.Attributes.Add("action", url);

TagBuilder buttonBuilder = new TagBuilder("input");
buttonBuilder.MergeAttribute("type", "submit");
buttonBuilder.MergeAttribute("value", buttonText);

But how are the two different and when should I prefer one over the other?

1

There are 1 answers

0
Henrik Stenbæk On BEST ANSWER

By looking at the TagBuilder with dotPeek, I can see that Attributes is an SortedDictionary

From ctor:

this.Attributes = new SortedDictionary<string, string>(StringComparer.Ordinal);

Calling Add on a SotredSet ends out calling an internal function AddIfNotPresent(item)

public bool Add(T item)
{
  return this.AddIfNotPresent(item);
}

This means that Attributes.Add is the same as calling MergeAttribute without setting replaceExisting == true.

   public void MergeAttribute(string key, string value, bool replaceExisting)
    {
      ...

      if (!replaceExisting && this.Attributes.ContainsKey(key))
        return;
      this.Attributes[key] = value;
    }

So my advice will be to use MergeAttribute over Add and always specify replaceExisting for readability and to make sure not to have unexpected outcomes.