AttributeCollection.Contains Method (Attribute)


Determines whether this collection of attributes has the specified attribute.

Namespace:   System.ComponentModel
Assembly:  System (in System.dll)

public bool Contains(
	Attribute attribute


Type: System.Attribute

An Attribute to find in the collection.

Return Value

Type: System.Boolean

true if the collection contains the attribute or is the default attribute for the type of attribute; otherwise, false.

This collection has the specified attribute if the specified type of attribute exists in the collection, and if the value of the specified attribute is the same as the value of the instance of the attribute in the collection.

The difference between the Matches and Contains methods is that Matches calls the Match method on an attribute, and Contains calls the Equals method.

For most attributes, these methods do the same thing. For attributes that may have multiple flags, however, Match is typically implemented so that it returns true if any of the flags are satisfied. For example, consider a data binding attribute with the Boolean flags "SupportsSql", "SupportsOleDb", and "SupportsXml". This attribute may be present on a property that supports all three data-binding approaches. It will often be the case that a programmer needs to know only if a particular approach is available, not all three. Therefore, a programmer could use Match with an instance of the attribute containing only the flags the programmer needs.

The following code example checks to see whether the collection has a BrowsableAttribute set to true. It assumes that button1 and textBox1 have been created on a form.

private void ContainsAttribute() {
    // Creates a new collection and assigns it the attributes for button1.
    AttributeCollection attributes;
    attributes = TypeDescriptor.GetAttributes(button1);

    // Sets an Attribute to the specific attribute.
    BrowsableAttribute myAttribute = BrowsableAttribute.Yes;

    if (attributes.Contains(myAttribute))
       textBox1.Text = "button1 has a browsable attribute.";
       textBox1.Text = "button1 does not have a browsable attribute.";

.NET Framework
Available since 1.1
Return to top