Declarative Security Used with Class and Member Scope

Declarative security can be performed on classes, members, and nested classes. This section outlines the rules used to evaluate declarative security when applied to multiple levels of the same class.

Classes, Members, and Declarative Security

When using declarative security, method-level declarations override class-level declarations for demands and asserts. However, when you use Inheritance Demands and Link Demands, the following rules apply:

  • Inheritance Demands. When applied at the class level, an inheritance demand requires the specified permission in order to derive from the class. When applied at the method level, an inheritance demand requires the specified permission in order to override the method in a derived class. Because inheritance demands have different meanings for classes and methods, declarations can be applied to both the member and class levels independently.
  • Link Demands. When applied to both the class and member levels, link demands are evaluated sequentially. The end result is a union of both the permissions demanded.

For all other actions, the method level completely overrides and replaces the class level. If the security actions are different (for example, a demand at class level with an assert at method level), there is no interaction whatsoever and both are evaluated.

Nested Classes and Declarative Security

When you apply declarative security to classes, it does not propagate to any nested classes or methods of nested classes. Conversely, when you apply declarative security to nested classes or methods of a nested class, it does not propagate to the parent classes either. You should apply declarative security to nested classes as if they were separate classes.

The following example shows a hypothetical permission demanded on the class level of a class called Main. Within that class, a nested class called Nested is defined. In this example, the demand does not apply to the nested class.

<SomePermissionAttribute(SecurityAction.Demand, Unrestricted:=True)> Public Class Main
   ' This nested class is not influenced by the demand.
   Public Class Nested
      ' This method is not influenced by the demand.
      Public Sub MyMethod()
      End Sub
   End Class
End Class
[C#][SomePermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
class Main
{
   // This nested class is not influenced by the demand.
   class Nested
   {
      // This method is not influenced by the demand.
      public void MyMethod()
      {   
      }
   }
}

See Also

Security Demands | Code Access Security