Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .Net, why aren't attributes declared on interfaces returned when calling Type.GetCustomAttributes(true)?

In answer to this question I tried to use Type.GetCustomAttributes(true) on a class which implements an interface which has an Attribute defined on it. I was surprised to discover that GetCustomAttributes didn't return the attribute defined on the interface. Why doesn't it? Aren't interfaces part of the inheritance chain?

Sample code:

[Attr()]
public interface IInterface { }

public class DoesntOverrideAttr : IInterface { }

class Program
{
    static void Main(string[] args)
    {
        foreach (var attr in typeof(DoesntOverrideAttr).GetCustomAttributes(true))
            Console.WriteLine("DoesntOverrideAttr: " + attr.ToString());
    }
}

[AttributeUsage(AttributeTargets.All, Inherited = true)]
public class Attr : Attribute
{
}

Outputs: Nothing

like image 952
Wesley Wiser Avatar asked Nov 10 '10 17:11

Wesley Wiser


1 Answers

I don't believe attributes defined on implemented interfaces can be reasonably inherited. Consider this case:

[AttributeUsage(Inherited=true, AllowMultiple=false)]
public class SomethingAttribute : Attribute {
    public string Value { get; set; }

    public SomethingAttribute(string value) {
        Value = value;
    }
}

[Something("hello")]
public interface A { }

[Something("world")]
public interface B { }

public class C : A, B { }

Since the attribute specifies that multiples are not allowed, how would you expect this situation to be handled?

like image 129
cdhowie Avatar answered Oct 12 '22 23:10

cdhowie