devoured elysium
devoured elysium

Reputation: 105217

(.net) How to check if a given variable is defined with an attribute

I'd like to know if my textBox1 variable has the ABCAttribute. How can I check this?

Upvotes: 1

Views: 1581

Answers (3)

Rex M
Rex M

Reputation: 144162

You need a handle to the class (type) in which textBox1 exists:

Type myClassType = typeof(MyClass);

MemberInfo[] members = myClassType.GetMember("textBox1",
        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

if(members.Length > 0) //found a member called "textBox1"
{
    object[] attribs = members[0].GetCustomAttributes(typeof(ABCAttribute));

    if(attribs.Length > 0) //found an attribute of type ABCAttribute
    {
        ABCAttribute myAttrib = attribs[0] as ABCAttribute;
        //we know "textBox1" has an ABCAttribute,
        //and we have a handle to the attribute!
    }
}

This is a bit nasty, one possibility is to roll it into an extension method, used like so:

MyObject obj = new MyObject();
bool hasIt = obj.HasAttribute("textBox1", typeof(ABCAttribute));

public static bool HasAttribute(this object item, string memberName, Type attribute)
{
    MemberInfo[] members = item.GetType().GetMember(memberName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    if(members.Length > 0)
    {
        object[] attribs = members[0].GetCustomAttributes(attribute);
        if(attribs.length > 0)
        {
            return true;
        }
    }
    return false;
}

Upvotes: 6

Amal Sirisena
Amal Sirisena

Reputation: 1479

Do you mean the attributes as in:

<input class="textbox" type="text" value="search" ABC="val" name="q"/> 

In that case you can look up the attribute name in the control's Attribute collection.

WebForm Textbox control Attributes collection

If you mean attributes as in:

<ValidationPropertyAttribute("Text")> _
<ControlValuePropertyAttribute("Text")> _
Public Class TextBox _ 
...

then as the other posters have mentioned, you will have to use Reflection to determine if the control has a particular attribute.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 416101

Assuming textBox1 is, well, a TextBox control, then the answer is likely, "No, it doesn't have the attribute." Attributes are assigned to a Type, not an instance of the type. You can lookup what attributes are on any TextBox that ever was, is, or will be created right now (for a particular version of the framework).

Upvotes: 2

Related Questions