Combining PrincipalPermission Objects 

In most cases, you use PrincipalPermission objects in the same way that you use code access security permission objects. However, some aspects of permission functionality are more useful than others. For example, you can call the Intersect method to intersect two PrincipalPermission objects, but this might not be very useful because identity and role are intersected independently to return a PrincipalPermission object that represents the identity and role common to the intersected objects. In many cases, the returned object contains an empty string for the identity, the role, or both, and the object matches only an unauthenticated user (identity = "") or a user that does not belong to any roles (role = "").

Subset operations determine whether one PrincipalPermission object is a strict subset of another PrincipalPermission object. Effectively, this means that IsSubsetOf returns true only if the identities and roles match exactly, or if a role or identity is null. Therefore, IsSubsetOf has limited usefulness for this permission.

On the other hand, performing a union operation on two PrincipalPermission objects can be useful when you want to compactly represent a set of conditions that you want to test. For example, a union operation can be used when you want to check for the presence of either one identity or another identity. The following code shows a security check that succeeds if the Principal object represents fred or sally in the role of Administrator.

String id1 = "fred";
String role1 = "Administrator";
PrincipalPermission myPrincipalPerm1 = new PrincipalPermission(id1, role1);
String id2 = "sally";
String role2 = "Administrator";
PrincipalPermission myPrincipalPerm2 = new PrincipalPermission(id2, role2);
(myPrincipalPerm1.Union(myPrincipalPerm2)).Demand();
Dim id1 As String = "fred"
Dim role1 As String = "Administrator"
Dim myPrincipalPerm1 As New PrincipalPermission(id1, role1)
Dim id2 As String = "sally"
Dim role2 As String = "Administrator"
Dim myPrincipalPerm2 As New PrincipalPermission(id2, role2)
myPrincipalPerm1.Union(myPrincipalPerm2).Demand()

The following code shows how to specify the union of two permissions that accept any principal with the role1 and role2 values from the previous code.

((new PrincipalPermission(null, role1)).Union(new PrincipalPermission(null, role2))).Demand();
Dim pp1 As New PrincipalPermission(Nothing, role1)
Dim pp2 As New PrincipalPermission(Nothing, role2)
pp1.Union(pp2).Demand()

See Also

Reference

PrincipalPermission

Concepts

PrincipalPermission Objects