views:

42

answers:

1

When dealing with a collection of key/value pairs is there any difference between using its Add() method and directly assigning it?

For example, a HtmlGenericControl will have an Attributes Collection:

var anchor = new HtmlGenericControl("a");

// These both work:
anchor.Attributes.Add("class", "xyz");
anchor.Attributes["class"] = "xyz";

Is it purely a matter of preference, or is there a reason for doing one or the other?

+3  A: 

They are equivalent for your use, in this case, running this:

anchor.Attributes["class"] = "xyz";

Actually calls this internally:

anchor.Attributes.Add("class", "xyz");

In AttributeCollection the this[string key] setter looks like this:

public string this[string key]
{
  get { }
  set { this.Add(key, value); }
}

So to answer the question, in the case of AttributeCollection, it's just a matter of preference. Keep in mind, this isn't true for other collection types, for example Dictionary<T, TValue>. In this case ["class"] = "xyz" would update or set the value, where .Add("class", "xyz") (if it already had a "class" entry) would throw a duplicate entry error.

Nick Craver
This is true for AttributeCollection, but not necessarily true for all key-value collection types (NameValueCollection comes to mind)
Jimmy
@Jimmy - Correct, I'll amend to give an example.
Nick Craver
@Jimmy: I did a quick NameValueConfigurationCollection. They seem "functionally" the same. Is it a performance difference? @Nick: Yes, in this case, I was using an AttributeCollection when I wondered if there was a difference.
Atømix
@Atomiton: I meant System.Collections.Specialized.NameValueCollection, which is a multimap -- d.Add("foo", "bar"); d.Add("foo", "baz") yields d["foo"] = "bar,baz";
Jimmy
@Jimmy: Thanks for the example. That makes sense. The edited answer is much improved, too.
Atømix