soapergem
soapergem

Reputation: 9989

How can I tell if an instance variable using an interface has a custom attribute applied?

I want to be able to check for the presence of a custom attribute on an instance of a class, but I want to be able to perform that check from within that class's constructor. Take a look at this pseudo-code:

namespace TestPackage
{
    public class MyAttribute : Attribute { }
    public interface IMyThing { }

    public class MyThing : IMyThing
    {
        private bool HasMyAttribute { get; set; }

        public MyThing()
        {
            if (/* some check for custom attribute */)
            {
                HasMyAttribute = true;
            }
        }
    }

    public class MyWrapper
    {
        [MyAttribute]
        private readonly IMyThing _myThing;

        public MyWrapper()
        {
            _myThing = new MyThing();
        }
    }
}

The if-statement where I have the code comment is what I'd like to fill in. Is this possible?

Upvotes: 0

Views: 60

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112342

Attributes are defined statically in the code and are therefore static, they are not bound to instances. They are applied to a type or to members of this type.

In your case you could have your wrapper implement IMyThing and use it instead of the original type and then apply the attribute to the class.

[MyAttribute]
public class MyWrapper : IMyThing
{
    private readonly IMyThing _myThing;

    public MyWrapper()
    {
        _myThing = new MyThing();
    }

    public void DoMyThingStuff()
    {
        _myThing.DoMyThingStuff();
    }
}

And then you can check for the attribute like this:

bool CheckAttribute(IMyThing myThing)
{
    Type t = myThing.GetType();
    return t.GetCustomAttributes(typeof(MyAttribute), false).Length > 0;
}

If an object of the original class is passed, you get false. If a wrapper object is passed you get true.

You could also derive a class from the original class instead of creating a wrapper.

[MyAttribute]
public class MyDerived : MyThing
{
}

Upvotes: 2

nAviD
nAviD

Reputation: 3261

Use this constructor:

public MyThing
{
                HasMyAttribute =false;
                foreach (MemberInfo item in this.GetType().GetCustomAttributes(false))
                {
                        if(item.Name=="MyAttribute")
                            HasMyAttribute =true;
                }

}

Upvotes: -1

Related Questions