Attribute Inheritance

By default, custom attributes are not inherited. However, 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 have the PrincipalPermission attribute, which identifies the users or roles that can call functions of a particular class. The PrincipalPermission attribute is inheritable. In the example, ZClass functions are available to managers; YClass function calls are available to accountants. The YClass inherits and does not override MethodA from 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, which contradicts the PrincipalPermission attribute of YClass. YClass.MethodB remains 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");
       }
   }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.74.231