Question

How do I retrieve an attribute from an interface method my class implements?

Edit: I dont know the interface at the time, only the type of the class, or an instance of that class.

Edit: Added the inherited flag to the attribute but it has no effect.

[TestFixture]
public class MyTests {
    [Test]
    public void shouldGetMyAttribute() {
        var type = typeof (MyClass);
        var method = type.GetMethod("MyMethod");
        var attributes = method.GetCustomAttributes(true);
        var myAttribute = attributes.SingleOrDefault(x => x is MyAttributeAttribute);
        Assert.That(myAttribute, Is.Not.Null);
    }
}

public class MyClass : IMyInterface {
    public void MyMethod() {
        throw new NotImplementedException();
    }
}

public interface IMyInterface {
    [MyAttribute]
    void MyMethod();
}

[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MyAttributeAttribute : Attribute {}
Was it helpful?

Solution

typeof(MyClass).GetInterfaces() will return all interfaces implemented by the class. From there you can use code similar to what Ben M posted to navigate to the right method and attribute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top