In creating a custom security attribute (declaratively demanding custom permissions in my case), what practical difference is there in inheriting from SecurityAttribute or CodeAccessSecurityAttribute?
Reflecting on the types, CodeAccessSecurityAttribute does not seem to extend SecurityAttribute in any meaningful way, so I can only assume the type is used by the CAS system, but that’s code baked into the CLR, so I can’t read into it.
All the examples of custom permissions inherit from CodeAccessSecurityAttribute, but without an explanation as to why. Indeed, the PrincipalPermissionAttribute inherits from CodeAccsesSecurityAttribute, despite not strictly being a CAS-related permission (as it has different semantics and references the current principal, not the permissions granted to the calling assembly).
My question is academic – I can just inherit from CodeAccessSecurityAttribute to progress – but I would like to know why!
You’re correct in your assumption that the
CodeAccessSecurityAttributetype is used by the CLR itself. This is essentially an AOP-style behaviour offered by the CLR, which will verify (and/or modify, as appropriate) permissions created byCodeAccessSecurityAttributesubtype instances at runtime. The reason you can’t use SecurityAttribute for your base class is that the CLR only scans forCodeAccessSecurityAttributesubtypes. It will ignore other subtypes ofSecurityAttribute.As for why this is this case, I am unaware of any publicly available documentation. However, it seems safe to assume that it’s probably just an unfortunate byproduct of the .NET development history. It’s all too easy to imagine a scenario where non-CAS permissions were introduced late-ish in the design/development cycle of .NET 1.0, and support for these made it into the BCL but not into the CLR. Given the small number of developers who actually create non-CAS permissions, “fixing” the CLR permission attribute detector has probably never been considered important enough to merit any serious attention in any subsequent .NET release cycle.