API's that Suck

November 30, 2009

Why do I have to loops just to add to a collection?

Filed under: Uncategorized — Grauenwolf @ 6:55 am

Lets says you have a collection of strings representing email addresses in a MailAddressCollection. You want to add them to another MailAddressCollection you have to loop through them one item at a time.

  1. Dim source As New MailAddressCollection From {{"a@test.com"}, {"b@test.com"}, {"c@test.com"}}
  2. Dim target As New MailAddressCollection From {{"x@test.com"}, {"y@test.com"}}
  3. For Each item In source
  4.     target.Add(item)
  5. Next

Why doesn’t MailAddressCollection have an AddRange function like a sensible collection? Well, probably because there is nothing in the collection contract that says that it should. ICollection<T> only requires that an Add method be defined. With extension methods, that should be enough. Just hook into a generic AddRange method defined as such:

  1. Public Sub AddRange(Of T)(ByVal target As ICollection(Of T), ByVal source As IEnumerable(Of T))
  2.     For Each item In source
  3.         target.Add(item)
  4.     Next
  5. End Sub

Now when you call it, you get a nice and clean one-liner. And not just for MailAddressCollection, but for every class that implements ICollection<T>. Alas it doesn’t work on older collections that only implement ICollection, as that version doesn’t have an Add method.

  1. Dim source As New MailAddressCollection From {{"a@test.com"}, {"b@test.com"}, {"c@test.com"}}
  2. Dim target As New MailAddressCollection From {{"x@test.com"}, {"y@test.com"}}
  3. target.AddRange(source)

Ok, so what’s all this belly-aching about? Somehow this obvious little timesaver is missing from the numerous extension methods we got when LINQ was released.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: