Attribute Inheritance

Attribute Inheritance

By default, custom attributes are not inheritable. The AttributeUsage attribute can make an attribute inheritable. For the AttributeUsage attribute, set the Inherited option to true to enable inheritance.

Inheriting classes with attributes sometimes can cause interesting behavior. In the following code, ZClass is the base class, and YClass is the derived class. Both classes are adorned with the PrincipalPermission attribute, which identifies the users or roles that can call functions in a particular class. In the example, the ZClass function can be called by managers; YClass function calls are limited to accountants. The YClass inherits MethodA from the ZClass. Who can call YClass.MethodA? Because MethodA is not overridden in the derived class, YClass is relying on the implementation of MethodA in the base class, which includes any applicable attributes. Therefore, only managers can call the YClass.MethodA, whereas YClass.MethodB is available to accountants and not managers, as demonstrated in the following code:

using System;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Threading;

namespace Donis.CSharpBook{
    public class Starter{
        public static void Main(){
            GenericIdentity g=new GenericIdentity("Person1");
            GenericPrincipal p=new GenericPrincipal(g,
                new string [] {"Manager"});
            Thread.CurrentPrincipal=p;
            ZClass.MethodA();
            YClass.MethodA();
//          YClass.MethodB();    // Security exception.
        }
    }

    [PrincipalPermission(SecurityAction.Demand,
        Role="Manager")]
    public class ZClass {

        static public void MethodA() {
            Console.WriteLine("ZClass.MethodA");
        }
    }

    [PrincipalPermission(SecurityAction.Demand,
        Role="Accountant")]
    public class YClass: ZClass {

        static public void MethodB() {
            Console.WriteLine("ZClass.MethodB");
        }
    }
}