Consider the following code:
GroupPrincipal gp = ... // gets a reference to a group
foreach (var principal in gp.Members)
{
// How can I determine if principle is a user or a group?
}
Basically what I want to know is (based on the members collection) which members are users and which are groups. Depending on what type they are, I need to fire off additional logic.
Easy:
foreach (var principal in gp.Members)
{
// How can I determine if principle is a user or a group?
UserPrincipal user = (principal as UserPrincipal);
if(user != null) // it's a user!
{
......
}
else
{
GroupPrincipal group = (principal as GroupPrincipal);
if(group != null) // it's a group
{
....
}
}
}
Basically, you just cast to a type you're interested in using the as
keyword - if the value is null
then the cast failed - otherwise it succeeded.
Of course, another option would be to get the type and inspect it:
foreach (var principal in gp.Members)
{
Type type = principal.GetType();
if(type == typeof(UserPrincipal))
{
...
}
else if(type == typeof(GroupPrincipal))
{
.....
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With