Thursday, August 7, 2008

AttributeCollection.Contains Method Can Return True on an Empty Collection

I found a weird side effect, or so I first thought, of the Contains method of the AttributeCollection class.

'desc references an instance of my custom type derived from the PropertyDescriptor class
'desc.Attriutes is an EMPTY collection
dim x as boolean = desc.Attributes.Contains(New BrowsableAttribute(true))

Since desc.Attributes is an empty collection, calling the Contains method with any value couldn't possibly return anything but false, right?!?!? But as it turns out, the above statement will return True. This seemed absolutely crazy to me at first. But then I called:

'This time BrowsableAttribute is set false.
dim x as boolean = desc.Attributes.Contains(New BrowsableAttribute(false))

In this case x was set to False.

So my conclusion is that there must be some extra logic in the AttributeCollection.Contains method. It is not just your typical contains method that is just simply looking for an object match. It is smarter than that!

Since the BrowsableAttribute default is True, asking if the Attributes collection contains a default attribute value is in fact really true even when the Attributes collection is empty, or for that matter contains other attributes.

Now that I understand this, I am confident that this was the intended behavior of the Contains method. And if you really want to see if an Attribute is specified in the collection, regardless of its default setting, use the AttributeCollection.Matches method instead.

No comments: