0

Is there a way of applying attributes to interfaces such that the deriving interfaces also get the attribute?

using System;
namespace Attributes
{
    class Program
    {
        static void Main(string[] args)
        {
            GetAttributes<IBaseInterface>();    //  Writes Hello World! to console
            GetAttributes<IModuleInterface>();  //  Doesnt get the MyAttribute
            Console.ReadKey();
        }

        static void GetAttributes<T>()
        {
            var a = typeof(T).GetCustomAttributes(typeof(MyAttribute), true);
            if (a.Length > 0)
                Console.WriteLine((a[0] as MyAttribute).Abc);
        }
    }

    [AttributeUsage(AttributeTargets.Interface, Inherited = true)]
    public class MyAttribute : System.Attribute
    {
        public string Abc;
    }

    [MyAttribute(Abc = "Hello World!")]
    public interface IBaseInterface
    {

    }

    public interface IModuleInterface : IBaseInterface
    {

    }
}

The IBaseInterface has the MyAttribute but the same attribute is not inherited by the derived IModuleInterface.

Question: Can attributes of a base interface be somehow applied to derived (extended) interfaces? If yes how and if not why not? Also can you suggest some good articles on this topic?

  • 1
    This has been answered on: http://stackoverflow.com/questions/12106566/attribute-on-interface-members-does-not-work Another interesting approach is: http://stackoverflow.com/questions/540749/can-a-c-sharp-class-inherit-attributes-from-its-interface – Cat_Clan Nov 25 '15 at 18:31
  • Also this is a good read on the topic and a more or less formal stand from Microsoft employees: http://bradwilson.typepad.com/blog/2011/08/interface-attributes-class-attributes.html – Cat_Clan Nov 25 '15 at 18:40

0 Answers0